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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *