Custom confirm dialog with JavaScript

supergiox picture supergiox · May 31, 2012 · Viewed 18.6k times · Source

I would like to create a JavaScript function similar to confirm() that shows a dialog (a div with a question and 2 buttons) and returns true if the user clicks "Ok" or false otherwise.

Is it possible to do that using JavaScript/jQuery but without plugins (e.g. jQuery UI or Dialog)? Because I'm trying to reduce size and round trip times...

I tried to write this code, but I don't know how to make the function "wait" for the user click.

I would like to use my function in this way:

answer=myConfirm("Are you sure?")

In this way I could use the same function in several contexts, simply changing the question passed as a parameter. This is the same behavior of confirm()

Answer

georgebrock picture georgebrock · May 31, 2012

Rather than waiting for the user's input and then returning from the function, it is more common in JavaScript to provide a callback function that will be called when the action you're waiting for is complete. For example:

myCustomConfirm("Are you sure?", function (confirmed) {
    if (confirmed) {
        // Whatever you need to do if they clicked confirm
    } else {
        // Whatever you need to do if they clicked cancel
    }
});

This could be implemented along the lines of:

function myCustomConfirm(message, callback) {
    var confirmButton, cancelButton;

    // Create user interface, display message, etc.

    confirmButton.onclick = function() { callback(true); };
    cancelButton.onclick = function() { callback(false); };
}