J. Middelkamp J. Middelkamp - 2 months ago 40
Javascript Question

How to trigger the DOMNodeInserted event after injecting HTML with jQuery

In one of our projects we load slides into our webpage with use of AJAX. After the slides are loaded I want jQuery to execute a plugin on all new injected elements automatically.

This is the code I found else where but it didn't do the trick. Also I've tried to replace

.on
function with the
.bind
function but then the whole site died and JavaScript crashes with an overflow.

function loaded(selector, callback) {
//trigger after page load.
jQuery(function () {
callback(jQuery(selector));
});
//trigger after page update eg ajax event or jquery insert.
jQuery("body").on('DOMNodeInserted', selector, function (e) {
callback(jQuery(this));
});
}


I got the problem reproduced in a JSFiddle.

Answer

A. Wolff,

Thanks your answer solves my problem. I have edited the loaded function to the following:

function loaded(selector, callback) {
    //trigger after page load.
    jQuery(function () {
        callback(jQuery(selector));
    });
    var parentSelector = "* > " + selector;
    //trigger after page update eg ajax event or jquery insert.
    jQuery(document).on('DOMNodeInserted', parentSelector, function (e) {
        callback(jQuery(this).find(selector));
    });
}

Also I've forked a new working JSFiddle project for anyone who wants a full working example.

https://jsfiddle.net/9t8cahqv/

Thanks,

Jop

Comments