Detecting width changes with Mutation Observers
created for answer to http://stackoverflow.com/questions/29909400/is-there-a-event-invoked-when-a-blocks-width-changes
by UselessCode
HTML
<div id="foo">foo</div>
CSS
#foo {
border: 2px solid #f30;
width: 100px;
height: 100px;
transition: width 1s;
}
JavaScript
let foo = document.querySelector('#foo'),
oldWidth = foo.style.width,
observer = new MutationObserver(function(mutations) {
mutations.forEach(mutation => {
if (mutation.target === foo && mutation.attributeName === 'style' &&
oldWidth !== foo.style.width) {
alert('Width Changed!');
oldWidth = foo.style.width;
}
});
});
// configuration of the observer, just look for attribute changes:
var config = {
attributes: true
};
// start observing
observer.observe(foo, config);
// change the width so we can detect it
setTimeout(() => {
foo.style.width = '150px';
}, 500);