Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to call a jQuery plugin function on an element that hasn't yet been added to the DOM?

Tags:

I have a jQuery plugin that I am using:

$(document).ready(function(){
    $('.elements').fancyPlugin();
});

This works great until I start adding new elements:

$.get('ajax.html', function(data){
    $('#container').html(data);
});

I could call the plugin function again like this:

$.get('ajax.html', function(data){
    $('#container').html(data).find('.elements').fancyPlugin();
});

...except that the AJAX is happening inside another jQuery plugin that shouldn't have to know about the fancyPlugin().

How can I apply this plugin to all current and future elements?

like image 644
Andrew Avatar asked Jul 21 '11 19:07

Andrew


1 Answers

I think this will work in all browsers except IE:

document.body.addEventListener("DOMNodeInserted", function(event){
    var $elementJustAdded = $(event.target);
    if ($elementJustAdded.hasClass('elements')) {
        $elementJustAdded.fancyPlugin();
    }
}, false);
like image 74
Paul Avatar answered Oct 07 '22 19:10

Paul