Mutation Observers: detecting visibility changes inherited from a parent element

Viewed 3899

I am trying to detect when a target element becomes visible (visible or display:block) regardless of where it is placed in the HTML.

I tried using MutationObservers, however, the visibility change can only be detected if the observed element has a direct change in CSS properties. Thus, it ignores changes to its parent element.

var targetNode = document.getElementById('target');
var observer = new MutationObserver(function(){
    alert(targetNode.offsetWidth);
    }
);
observer.observe(targetNode,  { attributes: true, childList: true });

The PROBLEM occurs when a parent element CSS properties are changed and it is not detected/observed by the MuatationObserver attached to the child/target element as seen in in this jsfiddle. Is there a way (aside from using Intervals) for the observed DOM element to detect changes in CSS that is inherited from parents?

1 Answers

You can observe the parent and the child:

observer.observe(targetNode, options);
observer.observe(parentNode,  options);

var targetNode = document.getElementById('target');
var parentNode = document.getElementById('parent');
var observer = new MutationObserver(function (changes) { // or replace changes by just:  [ { target } ]
  const target = changes[0].target
 if (target === parentNode)
   alert('parent')

 if (target === targetNode)
   alert('target')

 console.log(target)
});

var options = { 
 attributes: true, 
  childList: true, 
  attributeFilter: ['style', 'class'] 
}

observer.observe(targetNode, options);
observer.observe(parentNode,  options);
<script>
function showParent() {
    document.getElementById("parent").style.display = "block";
}
function showChild() {
    document.getElementById("target").style.display = "block";
}
</script>

<button onclick="showParent()">showParent</button>
<button onclick="showChild()">showChild</button>
<div id="parent" style="display:none;"> 
  parent
  <div id="target" style="display:none;">target</div> 
</div>

Related