Search code examples
javascripthtmlcssmutation-observers

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>

Solution

  • 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);
        }
    }