Listening to events such as adding new elements in JavaScript
Solution 1
.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
Solution 2
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);
});
Solution 3
DOMNodeInserted is deprecated in DOM Level 3 recommendation. using them slows browsers down (they say). depending on what you need it for, it might make sense to trigger a custom event inside the code where you insert the element.
Related videos on Youtube
Comments
-
zeacuss almost 2 years
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?
-
Krish about 12 years@zeacuss: go here w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener
-
-
zeacuss about 12 yearsactually, I'm not the one adding the nodes, so I can't handle it where it is added.
-
yomexzo almost 10 yearsit is now deprecated.. see developer.mozilla.org/en-US/docs/Web/Guide/Events/…
-
Mikael Kessler over 9 yearsVery nice library! Solved my current issue and will definitely be using it on future projects. Thanks, Uzair!