How to detect when a div’s dimension changed with JavaScript?

Spread the love

Sometimes, we want to detect when a div’s dimension changed with JavaScript.

In this article, we’ll look at how to detect when a div’s dimension changed with JavaScript.

How to detect when a div’s dimension changed with JavaScript?

To detect when a div’s dimension changed with JavaScript, we use the ResizeObserver constructor.

For instance, we write

const outputSize = () => {
  console.log(textbox.offsetWidth, textbox.offsetHeight);
};
outputSize();

new ResizeObserver(outputSize).observe(textbox);

to create a ResizeObserver object by calling it with outputSize.

Then we call observe with textbox to watch for size change with the textbox element.

We get the width and height of the textbox with offsetWidth and offsetHeight.

Conclusion

To detect when a div’s dimension changed with JavaScript, we use the ResizeObserver constructor.

Leave a Reply

Your email address will not be published.