3

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,258
  • 2
  • 11
  • 33

2 Answers2

2

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
  • 103,437
  • 51
  • 275
  • 359
Navand
  • 416
  • 4
  • 11
  • This answer seems good too. It's much better than mine :) – Miu Mar 05 '21 at 06:47
  • 1
    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
1

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
  • 7,095
  • 3
  • 24
  • 37
  • 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