[javascript] Event when element added to page



Answers

The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).

So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)

Question

This was previously discussed here: How to do an action when an element is added to a page using Jquery?

The responder suggested triggering a custom event whenever a div was added to the page. However, I'm writing a Chrome extension and don't have access to the page source. What are my options here? I guess in theory I could just use setTimeout to continually search for the element's presence and add my action if the element is there.




There's a promising javascript library called Arrive that looks like a great way to start taking advantage of the mutation observers once the browser support becomes commonplace.

https://github.com/uzairfarooq/arrive/




You can use livequery plugin for jQuery. You can provide a selector expression such as:

$("input[type=button].removeItemButton").livequery(function () {
    $("#statusBar").text('You may now remove items.');
});

Every time a button of a removeItemButton class is added a message appears in a status bar.

In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.

Revisited answer

The answer above was only meant to detect that an item has been added to the DOM through the plugin.

However, most likely, a jQuery.on() approach would be more appropriate, for example:

$("#myParentContainer").on('click', '.removeItemButton', function(){
          alert($(this).text() + ' has been removed');
}

If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on.






Links