Categories
JavaScript Answers

How to listen for resize on div element with JavaScript?

Spread the love

Sometimes, we want to listen for resize on div element with JavaScript.

In this article, we’ll look at how to listen for resize on div element with JavaScript.

How to listen for resize on div element with JavaScript?

To listen for resize on div element with JavaScript, we can use the resize observer.

For instance, we write

const resizeObserver = new ResizeObserver((entries) => {
  entries.forEach(console.log);
});
resizeObserver.observe(document.getElementById("ExampleElement"));

to create the resizeObserver object with the ResizeObserver constructor.

We call it with a callback that runs when the element we’re observing is resized.

Then we call observer with the element that we want to watch for resizing for.

Conclusion

To listen for resize on div element with JavaScript, we can use the resize observer.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.