Overriding Javascript Confirm() while preserving the callback

Kyle Ross picture Kyle Ross · Oct 8, 2010 · Viewed 17.1k times · Source


To the point, I want to override the standard js confirm() function within a jQuery plugin. I have figured out how to do it with the simple function layout below.

function confirm(opts) {
   //code
}

Now, what I want to do is call another function within the confirm function above, like so...

function confirm(opts) {
   openModal(opts);
}

The openModal function will open a custom modal window with the message and required buttons. The buttons are both <span> with the id of either submit or cancel. submit returns true and cancel returns false. But now, how do I return either true or false based on the button clicked?

For example...

$('#openModal').live('click', function() {
   var opts = { title:'Modal Title', message:'This is a modal!' };
   var resp = confirm(opts);
   if(resp) 
      // user clicked <span id="submit"></span>
   else 
      // user clicked <span id="cancel"></span>
});

Hopefully you understand what I mean.

Answer

PleaseStand picture PleaseStand · Oct 8, 2010

This is possible but not exactly as you describe. The typical way the confirm function is used is:

if(confirm("Are you sure you want to submit this form?")) {
    form.submit();
}

In the above example, the button press is returned synchronously to the script. Execution is paused within the function until a button is pressed.

A "modal dialog" is just an overlay over the entire contents of an HTML web page. To the browser, buttons within such an overlay work the same way as buttons anywhere else within that page do.

Since JavaScript handles such button clicks asynchronously (i.e. using callback functions to handle events) rather than synchronously, the approach you are attempting will not work.

You would need to change all parts of the code that use the confirm function to look like this:

confirm("Are you sure you want to submit this form?", function(result) {
    if(result) {
        form.submit();
    }
});

This would work just as registering an event handler with jQuery itself does. Script execution continues immediately, skipping past all the code in the anonymous function. Later, the browser will call that function indirectly through a JavaScript event handler that you register within the confirm function, its purpose to call the callback function with either true or false as appropriate.