jQuery event to detect any new element in the DOM
have you ever been in a situation where you need to get all the elements that gets inserted into a web page after it has been loaded? like when a new html content has been loaded using ajax then appended to a web page’s body.
In this tutorial we’re going to write a custom jQuery event that will trigger anytime an html element is added to our webpage, the event will return a list of all the new elements in a variable that we can use on the callback function like we used to do on any regular jquery event method.
So our event method will look like:
$("body").domInsert(function(element){
console.log(element)
})
and here’s the declaration code of the new jQuery event:
$.fn.domInsert = function (callback=0) {
console.log(this)
var listen = (function(){
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
return function( obj, callback ){
if( !obj || !obj.nodeType === 1 ) return;
if( MutationObserver ){
var obs = new MutationObserver(function(mutations, observer){
callback(mutations);
})
obs.observe( obj, { childList:true, subtree:true });
}
else if( window.addEventListener ){
obj.addEventListener('DOMNodeInserted', callback, false);
}
}
})();
listElm = $(this)[0];
listen( listElm, function(m){
var addedNodes = []
m.forEach(record => record.addedNodes.length & addedNodes.push(...record.addedNodes))
if(callback!=0)
callback(addedNodes)
});
};
So you just need to copy this code and past it at the beginning of your javascript, of course it goes without saying that you need to call the jQuery library before doing all of this.