Search code examples
javascriptjqueryfacebox

Can I bind action to a specific facebox?


I want to bind a function to the closing of a specific facebox? According to the limited documentation at facebox(at github) you could do something like this to bind actions.

$(document).bind('close.facebox', function() {
    //do stuff...
})

But the problem with this is that it will bind the same action to all faceboxes created on the page.

So how could I bind different functions to different faceboxes? I have tried a few variants without success (probably due to my not yet masterlevelskills of javascript and jQuery):

  • Bind one general function as proposed by the documentation and in the function figure out what facebox was closed and do the wanted thing.
  • Get handle to facebox when created and use that to bind the action:

    var fb = $.facebox('foo');
    fb.bind('close.facebox', function() { ...do stuff ...})
    
  • Call bind on the facebox directly like:

    $.facebox('foo').bind('close.facebox', function() { ...do stuff ...})
    
  • Probably more variants that I do not remember...

Please help me understand how I should do this (or why I should not try to do this).


Solution

  • After a quick look at the source I can think of a hack (!) to make this work:

    1. Override the facebox#close method with you own.
    2. The scope within this method will give you access to the "close" link which has just been clicked
    3. Now you can traverse "sideways" to your content and use e.g. a data attribute or class name to identify which box you're currently showing
    4. Based on that you can then make a decision what to do.

    Here's an example:

    HTML:

    <a href="#foo" class="facebox">Foo</a>
    <a href="#bar" class="facebox">Bar</a>
    <div id="foo">
        <div data-close="foo">Foo</div>
    </div>
    <div id="bar">
        <div data-close="bar">Bar</div>
    </div>
    

    JS:

    $.facebox.close = function(e) {
        var type = $(this).prev().find('div:first').data("close");
        switch (type) {
        case "foo":
            alert("FOO");
            break;
        case "bar":
            alert("BAR");
            break;
        }
        $(document).trigger('close.facebox');
        return false
    };
    
    $('a.facebox').facebox();
    

    Try it here: http://jsfiddle.net/SU3se/ .

    I believe that the plugin makes the assumption that you'll not use it on multiple "different" objects and since you can have only one facebox open at times, this "should" not be an issue. But I can see why someone might want to do it nevertheless.

    Please remember that my solution is a hack and really not very pretty. Maybe someone else can think of something better.