4

I know I can use ResizeObserver to detect when a div's size changes, but I would like to only know when the user resizes the div with the CSS property resize: both, and not when the page gets resized.

// Detect when user resizes element with the property resize: both;
div {
  resize: both;
  overflow: auto;
  border: 1px solid;
}
<div>
  Hi!
</div>
KetZoomer
  • 2,701
  • 3
  • 15
  • 43

2 Answers2

3

You can use ResizeObserver:

const observer = new ResizeObserver(mutations => {
  console.clear()
  console.log(mutations[0].contentRect.width, mutations[0].contentRect.height)
});

observer.observe(test);
#test {
  resize: both;
  overflow: auto;
  border: 1px solid;
  width: 100px;
  height: 100px;
}
<div id='test'>Hi!</div>
vsync
  • 118,978
  • 58
  • 307
  • 400
Navand
  • 446
  • 4
  • 11
  • This answer seems good too. It's much better than mine :) – Miu Mar 05 '21 at 06:47
  • 3
    already did this, I was looking for a way to **only** detect when divs resized have been resized with the css property `resize: both`. **This does not answer the question.** – KetZoomer Mar 05 '21 at 06:59
  • I have deleted my answer because I've found a serious bug in it. I used mousedown/mouseup event. I think they may also be useful in your code. – Miu Mar 05 '21 at 07:05
2

You can use MutationObserver for this. Source here.

let observer = new MutationObserver(function(mutations) {
  console.log('Resized');
});

let child = document.querySelector('div');
observer.observe(child, { attributes: true });
div {
  resize: both;
  overflow: auto;
  border: 1px solid;
    width: 200px;
    height: 200px;
    
}
<div>
  Hi!
</div>
Diego Fortes
  • 8,830
  • 3
  • 32
  • 42
  • This seems great especially from the perspective of browser compatibility. [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#browser_compatibility) vs [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#browser_compatibility). And it only detects resize with mouse. – Miu Mar 05 '21 at 07:13
  • I have found a small problem. If `div` width is `%` or `vw`, the units seems stops working after resizing `div`, which means the width is fixed. – Miu Mar 05 '21 at 07:23
  • Thanks so much, only triggers with events from cursor. Works great! – KetZoomer Mar 05 '21 at 18:20
  • This also triggers if the dimensions have changed programmatically, not by the user. If you only want to listen for user changes, you can have a boolean variable that is set to `true` on `mousedown` and `false` on `mouseup`, and react to mutations only when the flag is `true`. – Mosh Feu Jul 16 '23 at 06:30