99

Concurrent visitors over the last 30 minutes. (~)

Peak concurrent visitors -
Yesterday: 0 / Today: 0

JS Resize Observer: Observing Element Size Changes

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).

JS
1
2
3
4
5
// 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).

JS
1
2
const 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: The content-box (content) size of the target
  • borderBoxSize: The border-box (content + padding + border) size of the target
JS
1
2
3
4
5
6
7
8
9
const ro = new ResizeObserver((entries, observer) => { entries.forEach(entry => { console.log(entry) }) }) ro.observe(element1) ro.observe(element2) // ...

ResizeObserverEntry structure

# observer

References the instance whose callback is running.

resize observer entry object

# Methods

# observe

Starts observing the target element.

JS
1
2
3
4
5
6
7
8
9
10
const 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.

JS
1
2
3
4
5
6
7
8
9
10
11
const 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.

JS
1
2
3
4
5
6
7
8
9
10
const 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