13

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?

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know those even existed! I do need to support IE9- though :( and those comments on performance hits aren't very reassuring. I know I didn't specify that in the question so your answer is correct but I do need to take all of it into consideration. Is there a hybrid approach that, at the very least, supports IE9-?
For browsers that don't support the above, you might need to roll out a timer which periodically checks the children of the parent element and trigger some callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.