How to make a function return result only after click?

Asked

Viewed 352 times

1

When using the function confirm() in Javascript, it’s usually like this:

var resultado = confirm("Deseja realmente confirmar?");
if(resultado){
    //confirmou...
}

I wonder if there is any way to do the same thing with a function of its own, example:

var resultado = minhaCofirmacao("Deseja realmente confirmar?");
if(resultado){
    //...
}

Here is an example of the function (only with the practical parts of the question): FIDDLE

I tried to do this by creating a Listener for when the user clicked on the confirmation button of my function, but it returns before the user triggers the event by itself.

Is there any way to create this kind of return dependent on a user action other than with callback?

  • The problem is that the confirm is synchronous and the JS stops and waits for the answer. I think this will prevent/limit what you want. When you wanted to fire this question/confirmation request?

  • 3

    "other than callback?" -- yes, and no. You can do it in other ways, like with Promises, but it’s still not gonna be synchronous code like I think you expect.

  • Scenario: I have an item deleted from a list, it sends me this confirmation and, according to my answer, takes action. (she has some other options that the confirm() traditional does not possess, so it is not used).

  • @Kazzkiq, without using callback, I believe it is difficult (or little practical), because the JS is asynchronous by nature (what I think is great), and will show the "my Agreement" and continue its course. Anyway, I don’t understand the problem in moving the course of the application to a callback? If you can specify why you would not like to use callback so we can better understand your need, so maybe we can help you better.

1 answer

1

You can do everything through Jquery like this:

var div = $("<div />").addClass("popup").appendTo($("body"));

$("<button />").append("Confirmar?").appendTo(div).click(function() {
    var confirmou = confirm("Deseja realmente confirmar?");
    if (confirmou) {
        alert("Confirmou! =)");
    } else {
        alert("Não confirmou... =(");
    }
});

Note that I created a div with the popup class you created and then just added the button to that div. I hope you solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.