Timothy Khouri
Timothy Khouri

Reputation: 31845

With jQuery, how can I use the "live" method to alert when a new element is added?

First off, I don't want another plugin to do this... jQuery already has the functionality to do 99% of what I want with the live() method.

Basically, I want to change this:

$(".some-button").live("click", function() { alert('yay!'); });

into this:

$(".some-button").live(function() { alert('yay!'); });

So, what I'm saying is that I want to fire a method right away when an element is added to the page... jQuery can already do this SOOO close because that's how it adds the "click" even in my example above!

How can I achieve this without adding another plugin, but rather, just by using the same functionality as the "live" and "die" methods do?

Upvotes: 2

Views: 238

Answers (3)

trusktr
trusktr

Reputation: 45484

You can't do it with the .live() method.

It seems jQuery should add a feature to the .live() method so that if its used with a specific keyword like 'created' instead of an event name then it will let you execute a function for the created element. That'd be cool! For example, the ideal scenario would be like this:

$('.foobar').live('created', function() {
    // do something with each newly created .foobar element here.
});

Upvotes: 0

bbg
bbg

Reputation: 3072

Here's some code I've copied and pasted that seems to work in fiddle, at least on FF: http://jsfiddle.net/KQBzn/

$(document).bind('DOMNodeInserted', function(event) {
      alert('inserted ' + event.target.nodeName + // new node
            ' in ' + event.relatedNode.nodeName); // parent
});

source: http://forum.jquery.com/topic/how-to-get-notified-when-new-dom-elements-are-added

Upvotes: 4

user113716
user113716

Reputation: 322502

There isn't any cross-browser way to do this, and there's nothing in jQuery itself that allows it.

You'd have to use a plugin, or just manage invoking code for your new elements manually.

The the live()[docs] method and the delegate()[docs] method are only for event handling. The code you give them will only respond to browser events, not to DOM manipulation.


The reason .live() won't do this is because it does not run any code when adding new elements to the DOM. It isn't monitoring any DOM changes. Rather it is responding to events that bubble to the document, and invoking the handler if it matches the selector you gave it.

Upvotes: 2

Related Questions