Bind "insert into DOM event" for an element not yet attached

I am looking for something like this:

var div = document.createElement('div'); div.id = 'proprioceptiveDiv'; $(div).on('appendedToDOM', function() { // ... }); document.body.appendChild(div); // triggers above handler 

Does it exist? I use jQuery and don’t want to import the whole plugin or other library just for this ability, so I'm only interested in a short solution.

+6
source share
2 answers

You can use Mutation Events , but events have been flagged as deprecated in the DOM Events specification because the design of the API is erroneous.

The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been fully and functionally implemented in all user agents. In addition, there were criticisms that the interface, as provided, poses a performance and implementation problem. DOM4 provides a new mechanism using the MutationObserver interface, which takes into account the use cases that mutational events solve, but in a more advanced way. Thus, this specification describes mutation events for reference and the completeness of obsolete behavior, but does not allow the use of the MutationEvent interface.

One simple parameter uses the .trigger() method:

 var $div = $(div).on('appendedToDOM', function() { console.log('appended'); }); // ... $div.appendTo('body').trigger('appendedToDOM'); 

You can also create a helper function that adds an element and fires a custom event:

 function append(elem, target, cEvent) { if (typeof target === 'undefined') var target = document.body; if (typeof cEvent === 'undefined') var cEvent = 'appendedToDOM'; $(elem).appendTo(target).trigger(cEvent); } // Usage append(element [, targetElement] [, customEvent]); 
+2
source
Answer

@Undefined gave me an idea. Since Mutation Events are deprecated, this is not a great solution, but either way:

 $(document).bind("DOMNodeInserted", function(e) { $(e.target).trigger('appendedToDOM'); }); 
+2
source

Source: https://habr.com/ru/post/953478/


All Articles