JS ResizeObserver
In this page:
What Is ResizeObserver?
ResizeObserver watches an element and reports when its size changes. This is more efficient and more accurate than listening for the window's resize event, since it reports changes to a specific element's box, not just the overall viewport.
Example: What Is ResizeObserver?
<div id="box" style="width: 200px;">Resize me</div>
<script>
const observer = new ResizeObserver(() => console.log("Size changed"));
observer.observe(document.getElementById("box"));
</script>
Reading the New Size
The contentRect property gives the content box size of the observed element. This gives you the actual rendered dimensions after layout, which is more reliable than reading offsetWidth/offsetHeight manually after every possible resize trigger.
Example: Reading the New Size
<div id="box">Box</div>
<script>
const observer = new ResizeObserver((entries) => {
console.log(entries[0].contentRect.width, entries[0].contentRect.height);
});
observer.observe(document.getElementById("box"));
</script>
Responding to Size Changes
You can change styles when the element grows or becomes smaller. This makes it possible to build responsive components that adapt their own layout based on their container's size, not just the overall window size.
Example: Responding to Size Changes
<div id="box">Box</div>
<script>
const observer = new ResizeObserver((entries) => {
document.getElementById("box").style.background = entries[0].contentRect.width < 100 ? "red" : "green";
});
observer.observe(document.getElementById("box"));
</script>
Observing Multiple Elements
One ResizeObserver can watch several elements. The callback receives entries for changed elements. This lets you implement responsive component logic — like showing a compact layout only when a specific container shrinks below some size — for many elements with one observer.
Example: Observing Multiple Elements
<div id="a">A</div>
<div id="b">B</div>
<script>
const observer = new ResizeObserver((entries) => {
entries.forEach(entry => console.log(entry.target.id, "resized"));
});
observer.observe(document.getElementById("a"));
observer.observe(document.getElementById("b"));
</script>
Stopping Observation
Use unobserve for one element or disconnect when you no longer need the observer. As with other DOM observers, disconnecting or unobserving elements you no longer need to track keeps the page from doing unnecessary background work.
Example: Stopping Observation
<div id="box">Box</div>
<script>
const observer = new ResizeObserver(() => console.log("resized"));
const el = document.getElementById("box");
observer.observe(el);
observer.unobserve(el); // stop watching
</script>
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: