Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind "insertion into DOM event" for not-yet-appended element

I'm 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 this exist? I'm using jQuery and would rather not import a whole plugin or another library just for this ability, so I'm only interested in a short solution.

like image 503
Mark Vayngrib Avatar asked Sep 09 '13 11:09

Mark Vayngrib


2 Answers

You can use Mutation Events but the events have been marked as deprecated in the DOM Events specification, as the API's design is flawed.

The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. DOM4 provides a new mechanism using a MutationObserver interface which addresses the use cases that mutation events solve, but in a more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of the MutationEvent interface.

One simple option is using .trigger() method:

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

// ...

$div.appendTo('body').trigger('appendedToDOM');

You can also create a helper function that appends the element and triggers 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]);
like image 109
undefined Avatar answered Oct 13 '22 02:10

undefined


@Undefined's answer gave me an idea. As Mutation Events are deprecated, this is not a great solution, but anyway:

$(document).bind("DOMNodeInserted", function(e) {
  $(e.target).trigger('appendedToDOM');
});
like image 38
Mark Vayngrib Avatar answered Oct 13 '22 00:10

Mark Vayngrib