Jeff Camera
Jeff Camera

Reputation: 5544

jQuery: Can I automatically apply a plug-in to a dynamically added element?

I'm in the process of converting my web app to a fully AJAX architecture.

I have my master page that is initially loaded and a div container that is loaded with dynamic content.

I created a few jQuery plugins that I apply to certain elements in order to extend their functionality. I'd normally call the functions as follows during each page load:

$(document).ready(function () {

    // Enable fancy AJAX search
    $(".entity-search-table").EntitySearch();

});

This would find the appropriate div(s) and call the plugin to enable the necessary functionality.

In an AJAX environment I can't just apply the plugin during the page load since elements will be added and removed dynamically.

I'd like to do something like this:

$(document).ready(function () {

    // Enable fancy AJAX search
    $(".entity-search-table").live("load", function () {
        $(this).EntitySearch();
    });

});

Question: Is there any way that I can trigger an event when a <div> or other element that matches a selector is added to the DOM?

It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.

Thanks for any help!

Upvotes: 3

Views: 2187

Answers (4)

Jaime
Jaime

Reputation: 6814

Use the live binding in your plugin code directly

jQuery.fn.EntitySearch = function() {
   this.live(..., function(){ your plugin code });
   return this;
}

Upvotes: 0

Phrogz
Phrogz

Reputation: 303208

The DOM 2 MutationEvent is what you really want, but unfortunately it isn't supported by IE. You'll need to either use live()/ delegate() binding in the plug-in, or (as I did when I had to work around this) use callbacks from your AJAX loaders indicating the scope of what has changed.

Upvotes: 0

karim79
karim79

Reputation: 342635

Yes - take a look at liveQuery. Example:

$('.entity-search-table').livequery(function(){ 
    $(this).EntitySearch(); 
});

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630379

It seems incredibly wasteful to activate the plug-in every time an AJAX request completes. The plug-in only needs to be applied to the element once when it is first added to the DOM.

You can get the best of both worlds here, for example:

$("#something").load("url", function() {
  $(".entity-search-table", this).EntitySearch();
});

This way it's only applying the plugin to the .entity-search-table elements you just loaded, since we specified a context to $(selector, context) to limit it.

Upvotes: 1

Related Questions