ResizeObserver: observe() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2020.
Theobserve() method of theResizeObserver interface starts observing the specifiedElement orSVGElement.
In this article
Syntax
observe(target)observe(target, options)Parameters
targetA reference to an
ElementorSVGElementto beobserved.optionsOptionalAn options object allowing you to set options for the observation. Currently thisonly has one possible option that can be set:
boxSets which box model the observer will observe changes to. Possible values are:
content-box(the default)Size of the content area as defined in CSS.
border-boxSize of the box border area as defined in CSS.
device-pixel-content-boxThe size of the content area as defined in CSS, indevice pixels, before applying any CSS transforms on the element or its ancestors.
Return value
None (undefined).
Exceptions
None.
Examples
The following snippet is taken from theresize-observer-text.html(see source) example:
const resizeObserver = new ResizeObserver((entries) => { for (const entry of entries) { if (entry.contentBoxSize) { // Checking for chrome as using a non-standard array if (entry.contentBoxSize[0]) { h1Elem.style.fontSize = `${Math.max( 1.5, entry.contentBoxSize[0].inlineSize / 200, )}rem`; pElem.style.fontSize = `${Math.max( 1, entry.contentBoxSize[0].inlineSize / 600, )}rem`; } else { h1Elem.style.fontSize = `${Math.max( 1.5, entry.contentBoxSize.inlineSize / 200, )}rem`; pElem.style.fontSize = `${Math.max( 1, entry.contentBoxSize.inlineSize / 600, )}rem`; } } else { h1Elem.style.fontSize = `${Math.max( 1.5, entry.contentRect.width / 200, )}rem`; pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`; } } console.log("Size changed");});resizeObserver.observe(divElem);Anobserve() call with an options object would look like so:
resizeObserver.observe(divElem, { box: "border-box" });Specifications
| Specification |
|---|
| Resize Observer> # dom-resizeobserver-observe> |
Browser compatibility
Loading…