Sometimes, we want to detect whether an HTML element’s size has changed.
In this article, we’ll look at how to detect an HTML element that has changed in size.
ResizeObserver
The ResizeObserver API lets us watch for changes in the size of an HTML element.
For instance, we can write:
const div = document.querySelector('div')
const sleep = ms => new Promise((resolve) => setTimeout(resolve, ms));
(async () => {
for (let i = 0; i < 10; i++) {
const p = document.createElement('p')
p.textContent = 'hello'
div.appendChild(p)
await sleep(1000)
}
})();
new ResizeObserver(e => {
const [{
borderBoxSize,
contentBoxSize,
contentRect,
devicePixelContentBoxSize: [devicePixelBoxSize]
}] = e;
console.log(borderBoxSize, contentBoxSize, contentRect, devicePixelBoxSize)
}).observe(div);
We have a div that we want to watch for size changes.
And we have an async function that adds a p element to the div to change its size every second.
Then we use the ResizeObserver
with a callback to watch for size changes.
We call observe
to with the div
element object to watch for size changes of the div.
In the ResizeObserver
callback, we get an event object in the parameter that has info about the element being watched.
We get a few properties in the e
object.
The borderBoxSize
property lets us get the border-box size of the observed element.
The contentBoxSize
property lets us get the content box size of the observed element.
The contentRect
property lets us get the new size of the observed element.
The devicePixelContentBoxSize
property has the new content-box size in device pixels of the observed element.
These properties are all objects.
borderBoxSize
, contentBoxSize
, and contentRect
properties has the blockSize
and inlineSize
properties which has the size in pixels depending on whether the element is a block or inline element.
contentRect
has the coordinates of the rectangle with the left
, right
, top
and bottom
properties.
left
and top
have the coordinates of the x and y top-left corner in pixels.
right
and bottom
have the coordinates of the x and y bottom-right corner in pixels.
x
and y
also have the coordinates of the x and y top-left corner in pixels.
Conclusion
We can use the ResizeObserver API to watch for size changes of a given HTML element.