J. Middelkamp
J. Middelkamp

Reputation: 141

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.

Upvotes: 9

Views: 19238

Answers (3)

J. Middelkamp
J. Middelkamp

Reputation: 141

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

Upvotes: 5

Harpreet Singh
Harpreet Singh

Reputation: 2671

Another way of doing this might be, watch for a DOM

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (!mutation.addedNodes) return

    for (var i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      var node = mutation.addedNodes[i]
      if ($(node).hasClass("some class")) {
        $(node).remove()
      }

      //or with id

      if ($(node).attr("id") == "someId") {
        $(node).remove()
      }

      //or any other selector
    }
  })
})

observer.observe(document.body, {
  childList: true,
  subtree: true,
  attributes: false,
  characterData: false
})

To Stop Observe, use

observer.disconnect();

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74420

Event is fired on container DIV level so your selector isn't matching. You could use instead:

loaded(":has([title])", function(element) {
   element.tooltip();
});
/**/
jQuery(document).on('DOMNodeInserted', selector, function(e) {
   callback(jQuery(this).find('[title]'));
});

-jsFiddle-

Upvotes: 2

Related Questions