Search code examples
javascriptjqueryfancybox

How do I globally handle onClose event of fancybox?


I am using Fancybox in my application. Now to handle the close event we write something like:

$(".fancybox").fancybox({onClose:function(){alert('blah');}}

as seen on this doc page:

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

However I want to write something common and global to all fancybox that gets run everytime for any of the fancybox. How do I do that? In short I don't want to write the code of onClose on each fancybox and don't want it to be dependent upon class,id (Eg. .fancybox in this case). How do I do that? I tried to write:

$.fancybox({onClose:function(){alert('blah');}}

but it doesn't work and from the docs it looks like this is the function for opening progammatically.


Solution

  • I'm not sure if this is the best solution but I would go for a pub/sub pattern so, in your fancybox you should do something like that.

    $( ".fancybox" ).fancybox( {
        onClose: function () {
            $( window ).trigger( 'fancyboxClosed' );
        }
    } );
    

    Then, somewhere in your code:

    $( window ).on( 'fancyboxClosed', function () {
        // Your global function for fancybox closed
    } );
    

    I don't know very much about your purpose but have in mind you can always pass a named function instead of an anonymous one so you always trigger the same function.

    The above example should be the way to go if you want to make different things depending on each fancybox.

    Also, you can attach the event to whatever object you want. Just used window for convenience.

    Edit

    You can also edit your fancybox source to do that (edit for 1.3.4) just add $(window).trigger('fancyboxClosed'); to around line 953.