The Resize Observer API provides a way to notify an observer if an element it is registered on is re-sized in any way.
The ResizeObserver
class is provided with an observer that will be called on every resize event.
const resizeObserver = new ResizeObserver(entries => {
for(const entry of entries) {
if(entry.contentBoxSize)
consoleo.log("element re-sized")
}
})
resizeObserver.observe(document.querySelector("div"))
Whenever the divs are re-sized, “element re-sized”
is printed on the console.
Let’s see an example of how to use the Resize Observer API
.
We have range sliders here. If we slide them, they will change the height and width of the <div> #resizeBox
.
We registered a ResizeObserver
on the <div #resizeBox>
, with an observer. It will display the message indicating that the box has been re-sized and the current values of its height and width.
Try to slide the range sliders; you will see the <div #resizeBox>
change in width and height. Also, we see that the info is displayed in the <div #stat>
box.
Try it live here: ResizeObserver.
Free Resources