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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With