Detecting when a new DOM Element is added in HTML/JavaScript

This post is a half reminder… I want to be notified when elements are insert into a box. The box contains list of elements. The user experience is: User adds an element to the box. Element is prepended to the box with a “new_addition” class that styles the background of the element. 4 seconds later the background should be removed.

Using jQuery’s (v 1.4) ‘live’ binding and the DOMNodeInserted event we can do this very easily:

('#set_list').live('DOMNodeInserted',function(event){
 
  setTimeout("$('#"+event.target.id+"').removeClass('new_addition')",4000);
 
});

Here’s a JSFiddle.net example: http://jsfiddle.net/MZeLk/12/ — Open your Firebug console to see the count of items you add in realtime.

As the piggy says, “Th-th-th-that’s all folks!”