JS Resize Observer: Observing Element Size Changes
# Overview
Resize Observer is an API that watches a target element for size changes and runs a callback.
You can use it without the various problems, such as infinite callback loops or circular dependencies, that can occur when you handle size changes yourself.
You initialize an observer with an instance (ro) created by new ResizeObserver, and specify the target to observe (Element).
The constructor takes 1 argument (callback).
12345// Initialize the observer const ro = new ResizeObserver(callback) // Register the target (element) to observe ro.observe(element)
# Callback
When a target is registered or its size changes, the observer runs the callback.
The callback takes 2 arguments (entries, observer).
12const ro = new ResizeObserver((entries, observer) => {}) ro.observe(element)
# entries
entries is an array of ResizeObserverEntry instances, which represent the targets observed with the .observe() method.
ResizeObserverEntry contains the following properties.
contentRect(legacy): The rectangle information of the target (DOMRectReadOnly)target(legacy): The target element (Element)contentBoxSize: Thecontent-box(content) size of the targetborderBoxSize: Theborder-box(content + padding + border) size of the target
123456789const ro = new ResizeObserver((entries, observer) => { entries.forEach(entry => { console.log(entry) }) }) ro.observe(element1) ro.observe(element2) // ...
# observer
References the instance whose callback is running.
# Methods
# observe
Starts observing the target element.
12345678910const ro1 = new ResizeObserver(callback1) const ro2 = new ResizeObserver(callback2) const div = document.querySelector('div') const button = document.querySelector('button') const textarea = document.querySelector('textarea') ro1.observe(div) // Observe the DIV element ro2.observe(button) // Observe the BUTTON element ro2.observe(textarea) // Observe the TEXTAREA element
# unobserve
Stops observing the target element.
1234567891011const ro1 = new ResizeObserver(callback1) const ro2 = new ResizeObserver(callback2) // ... ro1.observe(div) ro2.observe(button) ro2.observe(textarea) ro1.unobserve(button) // Nothing.. ro2.unobserve(button) // Stop observing the BUTTON element
# disconnect
Stops observing all elements that the ResizeObserver instance is observing.
12345678910const ro1 = new ResizeObserver(callback1) const ro2 = new ResizeObserver(callback2) // ... ro1.observe(div) ro2.observe(button) ro2.observe(textarea) ro2.disconnect() // Stop observing all elements `ro2` is observing (BUTTON, TEXTAREA)
# Examples
Thanks for reading to the end.
Likes and kind comments help keep this blog going!