deprecated : according to a comment by @Meglio below, the DOMNodeInserted
event DOMNodeInserted
deprecated and will be removed from the Internet at some genuine future time. For best results, start exploring the MutationObserver API .
see @dain answer below .
If you attach the 'DOMNodeInserted' event to a document or body directly, it will be executed every time something is inserted anywhere. If you want a callback to be triggered only when a certain type of element is added, it would be wise to use delegated events .
Usually, if you add a class of elements to the DOM, you add them to the common parent. Therefore, attach an event handler as follows:
$('body').on('DOMNodeInserted', '#common-parent', function(e) { if ($(e.target).attr('class') === 'myClass') { console.log('hit'); } });
Basically the same answer as Myke above , but since you are using a delegated event handler rather than a direct event handler, the code there will be fired less often.
Note:
$('body').on('DOMNodeInserted', '.myClass', function(e) { console.log(e.target); });
It seems to work too ... but I don't know why.
Ziggy Jul 19 '13 at 20:03 2013-07-19 20:03
source share