I need to create an event listener such that, when a new element is added to the document, or any of its child, my event handler gets called.
Any ideas how to do this using?
To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document. querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.
The most common events you might “listen out for” are load , click , touchstart , mouseover , keydown .
.bind('DOMNodeInserted DOMNodeRemoved')
this are the events to check element is inserted or removed.
bind on parent element this event.
and call your function in handler
js fiddle demo : http://jsfiddle.net/PgAJT/
click here for example... http://help.dottoro.com/ljmcxjla.php
Mutation events are deprecated, use Mutation Observer instead. You can also use arrive.js library, it uses Mutation Observer internally and provides a nice simple api to listen for elements creation and removal.
$('#container').arrive('.mySelector', function(){ var $newElem = $(this); });
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