Search code examples
jquerycallbacksimplemodal

SimpleModal Confirm Override: Would like callback to return true or false instead of URL redirect


Hi I am a jquery newbie and trying to use the simplemodal plugin. Before this attempt my code was

isYes = confirm("Are you sure . . . "?); 
return isYes;

The simplemodal demo does a URL redirect. I would like to return true or false the way a default confirm button does.

Is this possible?

When I try this (Please see code below), the modal dialog pops up, but instead of waiting, it proceeds with the underlying button action before I can click anything!

This is how I call confirm:

confirm(confirm_message, function(isYes) { return isYes; });




function confirm(message, callback) {
    var isYes = false; 
    $('#confirm').modal({
        closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
        position: ["20%", ],
        overlayId: 'confirm-overlay',
        containerId: 'confirm-container',
        onShow: function(dialog) {
            var modal = this;

            $('.message', dialog.data[0]).append(message);

            // if the user clicks "yes"
            $('.yes', dialog.data[0]).click(function() {
                isYes = true;
                // call the callback
                if ($.isFunction(callback)) {
                    callback.apply(this, jQuery.makeArray(isYes));
                }
                // close the dialog
                modal.close(); // or $.modal.close();

            });


        }
    });
    return isYes;
}

Solution

  • Steps to make this work:

    1) Remove simplemodal-close from the No button

    2) In confirm.js, change:

    // if the user clicks "yes"
    $('.yes', dialog.data[0]).click(function () {
        // call the callback
        if ($.isFunction(callback)) {
            callback.apply();
        }
        // close the dialog
        modal.close(); // or $.modal.close();
    });
    

    To:

    // if the user clicks "yes"
    $('.buttons div', dialog.data[0]).click(function () {
        var link = $(this);
        // call the callback
        if ($.isFunction(callback)) {
            callback.apply(this, [link.hasClass('yes') ? true : false]);
        }
        // close the dialog
        modal.close(); // or $.modal.close();
    });
    

    3) Also in confirm.js, change:

    confirm("Continue to the SimpleModal Project page?", function () {
        window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';
    });
    

    To:

    confirm("Continue to the SimpleModal Project page?", function (response) {
        // do whatever you need to do with response
    });
    

    Hope that helps.

    -Eric