Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listening to events such as adding new elements in JavaScript [duplicate]

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?

like image 543
zeacuss Avatar asked Mar 12 '12 12:03

zeacuss


People also ask

Can I add an event listener to multiple elements in JavaScript?

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.

What does add event listener do in JavaScript?

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.

What events can you listen for JavaScript?

The most common events you might “listen out for” are load , click , touchstart , mouseover , keydown .


2 Answers

.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

like image 147
sandeep Avatar answered Sep 20 '22 09:09

sandeep


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); }); 
like image 33
Uzair Farooq Avatar answered Sep 21 '22 09:09

Uzair Farooq