Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver to check div height (mutation.type)

I wish to listen to the height of a div using MutationObserver, it however isn't firing when I add text to the innerHTML of the element I am trying to observe.

html:

<button onclick="myFunction()">click me</button>
<div id="support"></div>
<div id="info"></div>
<div id="text"></div>

js:

var myFunction = function() {
  var tmp = document.getElementById('text').innerHTML;
  document.getElementById('text').innerHTML = tmp + "herro<br>";
};

if ("MutationObserver" in window) {
  document.getElementById('support').innerHTML = "MutationObserver supported";
  var observer = new MutationObserver(function (mutations) { // <- this isn't firing
    mutations.forEach(function (mutation) {
      var tmp = document.getElementById('info').innerHTML;
      document.getElementById('info').innerHTML = tmp + mutation.type + "<br>";
    });
  });

  var observerConfig = {
    attributes: true,
    childList: true,
    characterData: true
  };
  nodes
  var targetNode = document.getElementById('text');
  observer.observe(targetNode, observerConfig);
}

codepen: http://codepen.io/basickarl/pen/xZXWoK?editors=101

I wonder what I am doing wrong.

like image 614
basickarl Avatar asked Sep 01 '25 10:09

basickarl


1 Answers

MutationObserver doesn't work for automatic height changes - it's for attribute/DOM changes/modifications. But ResizeObserver is designed for exactly this use case:

new ResizeObserver(function() {
  console.log("height of yourElement changed to:", yourElement.offsetHeight);
}).observe(yourElement);

It's supported in all modern browsers: https://caniuse.com/resizeobserver

like image 79
joe Avatar answered Sep 04 '25 00:09

joe