Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 609
sgcharlie Avatar asked Dec 28 '12 18:12

sgcharlie


People also ask

Which method is triggered when an element is added to the DOM?

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.

Can JavaScript trigger events?

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.

How DOM will be used in events in JavaScript?

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).


1 Answers

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.

like image 139
techfoobar Avatar answered Sep 24 '22 01:09

techfoobar