I have created a nested structure with two <div>
elements. I am monitoring changes in the width of the inner <div>
, which is set to width:auto;
. Despite adjusting the width of the parent <div>
, the mutation observer callback doesn't seem to trigger as expected when the target <div>
's width changes. What could be causing this issue?
// Targeting the element with changing display value
var blocker = document.querySelector('#blocker');
// Trigger to modify the display value of blocker
var trigger = document.querySelector('#trigger');
// Mutation observer to track attribute changes on blocker
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Was it the style attribute that changed? (Consider checking for other attribute changes too)
if (mutation.attributeName === 'style') {
alert(window.getComputedStyle(blocker).getPropertyValue('width'));
}
});
});
// Attaching the mutation observer to blocker, and focusing only on attribute value changes
observer.observe(blocker, {
attributes: true
});
// Modifying the style attribute of blocker upon trigger
trigger.addEventListener('click', function() {
$('#d').css('width', '300px');
}, false);
#d {
width: 200px;
}
#blocker {
width: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="d">
<div id="blocker" style="display:none">Stop!</div>
</div>
<div id="trigger">Show blocking element</div>