sgcharlie sgcharlie - 7 months ago 31
Javascript Question

Trigger Javascript Event on Add to DOM

Does anyone know how to trigger an event in javascript for an element after it has been added to the DOM?

The general idea is something like this:

var elem = document.createElement('div');
elem.addEventListener('ON_ADD_TO_BODY', function(){console.log(elem.parentNode)});
//... LATER ON ...
parentElemInBody.appendChild(elem); // <- Event is triggered here after append


There are some functions that shouldn't be triggered until you add the element to the DOM so it would make sense to delay execution until the element is added.

Is there a way to do this without explicitly needing to call them later on or should I be doing some hack that includes a
setTimeout
and a check to see if the element has been added to the DOM yet?

Answer

Use the DOMNodeInserted mutation event.

Docs here: https://developer.mozilla.org/en-US/docs/DOM/Mutation_events

Example usage as given in the above page:

element.addEventListener("DOMNodeInserted", function (ev) {
  // ...
}, false);

Note: 17th April, 2016

Mutation Events are deprecated as of now. The recommended approach now is Mutation Observers.