Search code examples
javascripthtmlcss

resize event not triggered on div


Take a look at this example: https://jsfiddle.net/vxun2Lgg/2/

I've attached a resize event listener on container div. After opening up dev tools, and modifying the width of container, resize callback does not get called. What am I missing?

PS: I am not interested in window resize event, only in container div.

var container = document.getElementsByClassName("container")[0];
container.addEventListener("resize", function() {
  console.log("resizing")
});
<div class="container"></div>


Solution

  • resize is only valid for the window. If supported you can use ResizeObserver.

    new ResizeObserver(() => console.log("resizing")).observe(container);
    

    Otherwise, you will probably have to poll using setInterval and check the size.