sgcharlie sgcharlie - 2 years ago 147
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
and a check to see if the element has been added to the DOM yet?

Answer Source

Use the DOMNodeInserted mutation event.

Docs here:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download