How to Use Resize Observer in JavaScript: Simple Guide
Use the
ResizeObserver API in JavaScript by creating a new observer with a callback function that runs when an element's size changes. Attach it to the target element using observe(), and stop observing with unobserve() or disconnect().Syntax
The ResizeObserver is created by passing a callback function that receives entries when observed elements resize. Use observe(targetElement) to start watching an element, unobserve(targetElement) to stop watching one element, and disconnect() to stop all observations.
javascript
const resizeObserver = new ResizeObserver(entries => { for (let entry of entries) { console.log('Element resized:', entry.target); console.log('New size:', entry.contentRect.width, 'x', entry.contentRect.height); } }); resizeObserver.observe(targetElement); // To stop observing one element resizeObserver.unobserve(targetElement); // To stop observing all elements resizeObserver.disconnect();
Example
This example shows how to watch a div element and log its new width and height whenever it changes size.
javascript
const box = document.getElementById('resize-box'); const resizeObserver = new ResizeObserver(entries => { for (let entry of entries) { const { width, height } = entry.contentRect; console.log(`Box size changed to ${width.toFixed(0)} x ${height.toFixed(0)}`); } }); resizeObserver.observe(box);
Output
Box size changed to 200 x 150
Box size changed to 250 x 180
Box size changed to 300 x 200
Common Pitfalls
- Not disconnecting the observer can cause memory leaks if elements are removed from the DOM.
- Observing many elements without need can hurt performance.
- Trying to observe non-Element nodes (like text nodes) will not work.
- Assuming the callback runs immediately; it only runs on size changes.
javascript
/* Wrong: Not disconnecting observer after use */ const observer = new ResizeObserver(() => { console.log('Resized'); }); observer.observe(document.body); // Later, if you remove elements or no longer need observation, call: observer.disconnect();
Quick Reference
| Method | Description |
|---|---|
| new ResizeObserver(callback) | Creates a new observer with a callback for resize events. |
| observe(element) | Starts observing size changes on the given element. |
| unobserve(element) | Stops observing the given element. |
| disconnect() | Stops observing all elements and clears the observer. |
Key Takeaways
Create a ResizeObserver with a callback to react to element size changes.
Use observe() to start watching an element and disconnect() to stop all observations.
Always disconnect observers when no longer needed to avoid memory leaks.
ResizeObserver only works on Element nodes, not text or comment nodes.
The callback runs asynchronously after size changes, not immediately on observe().