Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple mutation observer example in JavaScript doesn't work

I try to add a MutationObserver in my web page to track changes in an image src, but that doesn't work.

Here's the code used:

setTimeout(function() {
  document.getElementById("img").src = "http://i.stack.imgur.com/aQsv7.jpg"
}, 2000);

var target = document.querySelector('#img');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

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

observer.observe(target, config);
observer.disconnect();
<img src="http://i.stack.imgur.com/k7HT5.jpg" id="img" class="pic" height="100">
like image 642
Ravina Jasani Avatar asked Apr 27 '15 08:04

Ravina Jasani


People also ask

Is Mutation observer deprecated?

Use of Mutation Events is deprecated. Use MutationObserver instead. How do I find out the code responsible for triggering this message? It's likely due to a third-party library using the deprecated events.

How does a Mutation observer 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 observer in Javascript?

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.

Is Mutation Observer safe?

The MutationObserver API has near complete browser support, so we can use it safely in most — if not all — projects, should the need arise.


1 Answers

If you call disconnect method you will not receive notification anymore:

Quote from MDN

disconnect()

Stops the MutationObserver instance from receiving notifications of DOM mutations. Until the observe() method is used again, observer's callback will not be invoked.

setTimeout(function() {
  document.getElementById("img").src = "http://i.stack.imgur.com/aQsv7.jpg"
}, 2000);

setTimeout(function() {
      document.getElementById("img").src = "http://i.imgur.com/Xw6htaT.jpg"
    }, 4000);

var target = document.querySelector('#img');

var observer = new MutationObserver(function(mutations) {
  
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

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

observer.observe(target, config);

// otherwise
observer.disconnect();
observer.observe(target, config);
<img src="http://i.stack.imgur.com/k7HT5.jpg" id="img" class="pic" height="100">
like image 56
alessandro Avatar answered Oct 28 '22 09:10

alessandro