Search code examples
javascriptmutation-observers

Mutation Observer: How To Get Current Data From Mutation Record?


I have an <img> element whose src is changed dynamically. When the change occurs, the MutationObserver is fired and a MutationRecord is recorded. The problem is when I try to access the data from the MutationRecord, it's giving me the old data.

For example:

This is the original img element.

<img src="#" />

JS

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations){
console.log(mutations);
console.log(mutations[0].target.currentSrc);


});

var element = document.querySelector("#shirt-design");

observer.observe(element, {
    attributes: true,
    childList: true
});

After the src is changed dynamically, currentSrc should be something like "image.jpg". The MutationRecord shows the new data, but when I try to access it directly, it shows me the old data.

For example

console.log(mutations[0].target.currentSrc);  //shows #

console.log(mutations[0].target.currentSrc);  //SHOULD BE image.jpg

How can I access the current data from the MutationRecord?

EDIT

What I want from the MutationRecord is naturalWidth. It gives me 0 as if the src were #(which it was). How do I get naturalWidth of the current image?

console.log(mutations[0].target.naturalWidth);  //0
console.log(mutations[0].target.naturalWidth);  //SHOULD BE number > 0

EDIT 2

I even tried this code below(within the MutationObserver function) and the result was 0, which leads me to believe that the MutationRecord is from before the change or the observer is firing before the change is made.

console.log(document.querySelector("#shirt-design").naturalWidth); //0

What am I missing here?


Solution

  • So I figured out that MutationRecord was being retrieved before the <img> finished loading. All I had to do was wait for it to load and I was able to get the correct data from the MutationRecord.

    var observer = new MutationObserver(function(mutations){
      console.log(mutations);
      //wait for img to load
      document.querySelector("img").addEventListener("load", function(){
        console.log(mutations[0].target.currentSrc);
      });
    });