views:

52

answers:

2

Lets say I have the following code that returns number of anchor elements on a page:

function getLinkCount() {
    alert("Links:" + $("a").length);
}

If I call in on document ready it would work as expected. But what if now a new link gets inserted into a page dynamically through javascript, how can I get notified to run link counter function again? (I have no control over a script that could create a new link).

Basically I am looking for something similar to live() only that would be watching element creation event, something like:

$("a").live("create", getLinkCount);

that would trigger when a new element is created.

+4  A: 

You can use the .livequery() plugin for this, it runs for each element, including new ones, like this:

$("a").livequery(getLinkCount);

It's usually easier to do this when you create the elements though, for example if you're doing it after AJAX requests, the .ajaxComplete() handler may be a good place, for example:

$(document).ajaxComplete(getLinkCount);

This would run after each request, and since you normally create elements in your success handler, they would already be present when this complete handler runs.

Nick Craver
+2  A: 

You could use the DOMSubtreeModified event. For example:

$(document).bind('DOMSubtreeModified',function(){
  console.log("now there are " + $('a').length + " links on this page.");
})
Matt S
Does it work on Internet Exploder?
Mark Eirich
Good idea. Probably I can use even `DOMNodeInserted` event that has an actual element that was inserted as a target, so I can check whether or not it was an anchor before running a method.
serg
@Mark Yup doesn't work in IE...
serg