Jens Törnell
Jens Törnell

Reputation: 24748

Javascript eventlistener resize on div does not work

I try to get the eventlistener for resize to trigger but it does nothing.

  1. Run the code playground
  2. Drag the resize handle
  3. Expected is to have something outputted in the console.log

Why does nothing happends and how can I fix it?

/* Load event directly - FAIL */
document.querySelector("div").addEventListener("resize", () => {
  console.log("resize");
});

/* Wait until dom loads first - FAIL */
window.addEventListener("DOMContentLoaded", () => {
  document.querySelector("div").addEventListener("resize", () => {
    console.log("resize");
  });
});
div {
  width: 300px;
  height: 100px;
  background: #eee;
  resize: both;
  overflow: auto;
}
<div></div>

Upvotes: 0

Views: 85

Answers (1)

Paul Zaslavskij
Paul Zaslavskij

Reputation: 654

look at Resize_Observer_API docs

and there is my tiny prototype of it, like in your case:

html:

<div style="border: 1px solid #444;" id="textarea" contenteditable=""> some text</div> 
<div id="result"></div>

js:

function outputsize() {
   document.getElementById('result').innerHTML=`
   ${textarea.offsetWidth} ${textarea.offsetHeight}
   `
}
outputsize()

new ResizeObserver(outputsize).observe(textarea)

https://codepen.io/zaslavskij/pen/ZELZMYK

Upvotes: 1

Related Questions