Search code examples
javascriptmutation-observers

Observe implicit size changes on HTMLElements


While the MutationObserver allows monitoring explicit size changes to an HTMLElement's attribute, it doesn't seem to have a way/config that allow me to monitor implicit changes to it's size, which are computed by the browser.

Here's an example:

const observer = new MutationObserver(changes => {
  console.log('changed')
})

observer.observe(document.querySelector('#bar'), {
  attributes: true
})

document.querySelector('#foo').style.width = '200px'
.container {
  display: flex;
  align-items: stretch;
}

.child {
  width: 100px;
  height: 100px;
  margin: 0 2px;
  background: magenta;
}
<div class="container">
  <div class="child" id="foo"></div>
  <div class="child" id="bar"></div>
</div>

In the above example I'm changing the size of #foo, while observing #bar. #bar get's squished by #foo (it's width changes implicitly, since the browser computed it's width instead of me explicitly specifying it).

How can I detect such implicit size changes?


Solution

  • ...However, resize events are only fired on (sent to) the window object :: MDN

    New standard is :: Resize Observer

    new ResizeObserver(()=>console.log('bar dimension changed :: RO!')).observe(bar);
    

    But while it's for late Chrome only I suggest some library, like: CSS-Element-Queries

    <script src="css-element-queries-1.0.0/src/ResizeSensor.js"></script>
    <script src="css-element-queries-1.0.0/src/ElementQueries.js"></script>
    new ResizeSensor(bar, function(){ 
        console.log('bar dimension changed :: CSS-Element-Queries');
    });