Question

I have problem with fancybox.
I want to write a function that will run when the fancybox opened. How and when to call the function?

Example:

function myFunc() {
    alert("Opened!");
}

$('.content a').fancybox({ 
    'hideOnContentClick': false ,
    'callBackOnShow': myFunc(), // This not working! It call function when page is loaded
    'frameWidth': 920,
    'frameHeight': 530
});
Was it helpful?

Solution

Instead of myFunc() use myFunc. In javascript, a function with parens (and/or args) means you want to call it. A function name without them means you just want a reference to that function (which is probably what fancybox wants from you)

OTHER TIPS

This works

$("#element").fancybox({
    onStart     :   function() {
        return window.confirm('Continue?');
    },
    onCancel    :   function() {
        alert('Canceled!');
    },
    onComplete  :   function() {
        alert('Completed!');
    },
    onCleanup   :   function() {
        return window.confirm('Close?');
    },
    onClosed    :   function() {
        alert('Closed!');
    }
});

The newest way how to make it work is using afterShow or beforeShow:

$("a#registrace").fancybox({
  beforeShow   : function() {
    alert('its working!');
    validate_reg_form();
  }
});

I am loading registration form through ajax and I need to enable form-validation. In both cases (before and after), the content is already loaded.

Actually, on checking the docs, you have a typo in your option list...

You have callBackOnShow but it should be callbackOnShow (lower case b)

It should be:-

function myFunc() {
    alert("Opened!");
}

$('.content a').fancybox({ 
    'hideOnContentClick': false ,
    'callBackOnShow': myFunc, // no brackets
    'frameWidth': 920,
    'frameHeight': 530
});

Or, you can make an anonymous function...

$('.content a').fancybox({ 
    'hideOnContentClick': false ,
    'callBackOnShow': function() { alert('hello'); },
    'frameWidth': 920,
    'frameHeight': 530
});
'callbackOnShow': myFunc

lower case b as the options are case sensitive, and no brackets on myFunc, as you want to pass the function as an option, not call it.

As your title says "Jquery - fancybox and callback", You can a complete list of callback options for the fancybox 2 plugin found under the tab callbacks.

http://fancyapps.com/fancybox/#docs

If your using the old fancybox, maybe upgrading to fancybox2 as the new plugin has better features, with more control.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top