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.
You can use the
.livequery()plugin for this, it runs for each element, including new ones, like this:However, this plugin is out-of-date and is not recommended for current versions of jQuery.
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:This would run after each request, and since you normally create elements in your
successhandler, they would already be present when this complete handler runs.