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?
connectedCallback() When an element is added to the DOM, the connectedCallback method is triggered. From that moment we can be sure that its available in the DOM and we're able to safely set attributes, fetch resources, run setup code or render templates.
HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.
HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With