Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver — only do something if nodes added, not removed

Tags:

javascript

I have a MutationObserver that I'm using like so—

var config = {
  attributes: false,
  childList: true,
  characterData: false,
  subtree: true
};

var observer = new MutationObserver(function(mutations) {
  //need to call function1() only when nodes are ADDED, not removed
});

var startObserving = function () {
  target = document.getElementsByClassName("message-container")[0];
  observer.observe(target, config);
}

I need to both add and remove elements to/from the container that the MutationObserver is watching, but I only want to execute function1() when nodes are added. Is there a way to do this? I've been reading the MDN article but can't think of a way to do this. Any help would be appreciated!

like image 423
shan Avatar asked Jul 29 '16 16:07

shan


People also ask

How do mutation observers work?

MutationObserver is a Web API provided by modern browsers for detecting changes in the DOM. With this API one can listen to newly added or removed nodes, attribute changes or changes in the text content of text nodes.

What is Mutation observable?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

How to use Mutation observer in js?

This is done by setting the characterData property to true in the options object. Here's the code: let options = { characterData: true }, observer = new MutationObserver(mCallback); function mCallback(mutations) { for (let mutation of mutations) { if (mutation. type === 'characterData') { // Do something here... } } }


1 Answers

You should be able to check the addedNodes property on each of the mutations object to determine if elements were added. You’ll probably also want to validate that the type is childList.

Check out the MutationRecord page on the MDN.

Something like

var observer = new MutationObserver(function(mutations) {
  var hasUpdates = false;

  for (var index = 0; index < mutations.length; index++) {
    var mutation = mutations[index];

    if (mutation.type === 'childList' && mutation.addedNodes.length) { 
      hasUpdates = true;

      break;
    }
  }

  if (hasUpdates) {
    function1();
  }
});
like image 107
Jared Avatar answered Nov 02 '22 22:11

Jared