Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to react to a specific style attribute change with mutation observers?

I've been experimenting with Mutation Observers, so far I can apply the relevant functions to react upon adding, removing elements and so on. Now I am wondering, is there a way to target a specific change within a specific style attribute? I know I can observe for attribute changes, but I just don't know how to observe for a specific attribute modification. For example, if the z-index value of #childDiv changes to 5678, modify the style of the parentDiv in order for it to be shown.

<div id="parentDiv" style="display:none;">
  <div id="childDiv" style="z-index:1234;">
    MyDiv
  </div>
</div>
like image 251
JMZ Avatar asked Aug 18 '16 17:08

JMZ


1 Answers

As per the documentation use attributeFilter array and list the HTML attributes, 'style' here:

var observer = new MutationObserver(styleChangedCallback);
observer.observe(document.getElementById('childDiv'), {
    attributes: true,
    attributeFilter: ['style'],
});

var oldIndex = document.getElementById('childDiv').style.zIndex;

function styleChangedCallback(mutations) {
    var newIndex = mutations[0].target.style.zIndex;
    if (newIndex !== oldIndex) {
        console.log('new:', , 'old:', oldIndex);
    }
}
like image 126
wOxxOm Avatar answered Nov 08 '22 10:11

wOxxOm