We can use the ResizeObserver to watch for an element’s resizing.
For instance, if we have the following div:
<div style='background-color: yellow'>
hello world
</div>
Then we can use it by writing:
const div = document.querySelector('div')
const resizeObserver = new ResizeObserver(() => {
console.log(div.clientHeight);
});
resizeObserver.observe(div);
setTimeout(() => {
div.style.height = '200px'
}, 1000)
We get the div with the document.querySelector
method.
Then we use the ResizeObserver
by instantiating it with a callback.
In the callback, we log the clientHeight
to log the height of the div.
Next, we call resizeObserver.observe
to watch the div for size changes.
Then we call setTimeout
with a callback to set the height of the div to '200px'
.
So we should see that the console log will first log 18 and then log 200 since we change the size of the div to 200px high 1 second after setTimeout
is called.