Search code examples
javascriptjqueryjquery-eventsfacebox

How can I call a Jquery method on DOM elements that don't exist yet?


I'd like to use this lightbox plugin for some autocomplete links, that don't yet exist on my page.

You normally activate it using:

$(document).ready(function($) {
  $('a[rel*=facebox]').facebox() 
})

Since the a links aren't all on the page upon page load, I would normally look to the .live or .delegate methods to bind to an event, but in this case, what 'event' would I bind to to say "once this element is on the page, then call this method on it".

Or am I going about this totally the wrong way?


Solution

  • There is no such event.

    You need to invoke the plugin when you add the elements to the page.

       // create a new <a>, append it, and call the plugin against it.
    $('<a>',{rel:"facebox"}).appendTo('body').facebox();
    

    This example creates a new <a> element. If you're getting some elements from an AJAX response, call it against those:

    var elems = $( response );
    
    elems.filter( 'a[rel="facebox"]' ).facebox(); // if the <a> is at the top level
    elems.find( 'a[rel="facebox"]' ).facebox();   // if the <a> is nested
    
    elems.appendTo('body');