cstack
cstack

Reputation: 2232

How can I listen for an element being inserted into the DOM with jQuery without using custom triggers?

I want to listen for another piece of code that inserts some html into the page. I don't control that code, so I can't do .trigger('custom_event') and $(document).on('custom_event')

Additionally, the inserted div that I want to listen for is nested inside of the inserted html.

Here's what I have right now:

$(document).on('DOMNodeInsertedIntoDocument', "#inserted", function () {
    console.log("Inserted into document:", $(this));
});

$(document).ready(function () {
    var new_node = $('<div><div id="inserted">New Div</div></div>');
    $("body").append(new_node);
});

http://jsfiddle.net/AeHxQ/5/

Why doesn't the event get triggered?

Upvotes: 2

Views: 2936

Answers (1)

Jamie Mason
Jamie Mason

Reputation: 4196

You can use CSS animations with a little JavaScript, to detect when an element has been added to the DOM. The technique is explained here: http://davidwalsh.name/detect-node-insertion

Upvotes: 2

Related Questions