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.
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]);
@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');
});
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