Search code examples
javascriptjqueryfancybox

Javascript/Jquery Callback for Fancybox Yes No Confirm


I'm trying to implement a fancy Yes No confirm and I'm having problems getting the callback to work as needed. The example below is using Fancybox v2.

The problem with the code below is that the function "do_something" is being call when HREF "Test" is clicked and not being called when the user clicks #fancyConfirm_ok.

function fancyConfirm(msg,callback) {
    var ret;
    jQuery.fancybox({
        'modal' : true,
        'content' : "<div style=\"margin:1px;width:240px;\">"+msg+"<div style=\"text-align:right;margin-top:10px;\"><input id=\"fancyconfirm_cancel\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\"Cancel\"><input id=\"fancyConfirm_ok\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\"Ok\"></div></div>",
        'afterShow' : function() {
            jQuery("#fancyconfirm_cancel").click(function() {
                ret = false;
                //jQuery.fancybox.close();
                $.fancybox.close();
            })
            jQuery("#fancyConfirm_ok").click(function() {
                ret = true;
                jQuery.fancybox.close();
            })
        },
        'afterClose' : function() { 
            if (typeof callback == 'function'){ 
                callback.call(this, ret); 
            } else {
                var callback_type = typeof callback;
                alert(callback_type);
            }
        }
    });
}
<a href="#" onclick="fancyConfirm('Are you sure you want to delete?',  do_something('a', 'b') );return false;">Test</a>

Solution

  • Your method "do_something('a', 'b')" will be executed whenever user clicks on the link and the returned result will be passed as the second parameter to the "fancyConfirm" method. This is why your parameter "callback" is always "undefined".

    There is also a problem with fancyBox - "afterClose" callback gets called twice - before opening and after closing (this will be changed in the next release).

    I would bind a click event on the link and call a callback when user clicks on one of the buttons, like - http://jsfiddle.net/xcJFY/1/