3urdoch 3urdoch - 1 year ago 56
HTML Question

Is there a jquery event that fires when a new node is inserted into the dom?

Is there an event jquery fires on a dom element when it is inserted into the dom?

E.g. lets say I load some content via ajax and add it to the DOM and in some other piece of javascript I could add an event using .live() so that when an event matching a specific selector is added to the DOM the event fires on said element. Similar to $(document).ready() but on content that is added to the DOM dynamically.

What I am dreaming of:

$('.myClass').live('ready', function() {
alert('.myClass added to dom');

If jquery doesn't support such a thing then is there another way I could achieve this functionality without modifying the code that actually does the initial dom manipulation?


The .livequery() plugin still serves this niche need, like this:

$('.myClass').livequery(function() {
  alert('.myClass added to dom');

If you pass it just a callback function like above, it'll run for each new element it finds, both initially and as they're added. Inside the function this refers to the just-added element.

.live() listens for events that bubble, so doesn't fit this "when elements are added" situation, in that respect, .livequery() (the plugin) wasn't completely replaced by the addition of .live() to core, only the event bubbling portion (for the most part) was.