Skip to content

observeResize

Calls callback each time the size of element changes, with a ResizeObserver dedicated to it. Like ResizeObserver itself, it is also called once soon after it starts observing.

To limit how often it runs, wrap the callback with debounce or throttle from helpers4/function. Without ResizeObserver, it does nothing and returns a function that does nothing.

Available since v3.1.5

import { observeResize } from '@helpers4/browser';
// or, from the all-in-one package (same code, one install):
import { observeResize } from 'helpers4/browser';
observeResize(element: Element, callback: function, options: ObserveResizeOptions): function
ParameterTypeDescription
elementElementThe element to observe
callbackfunctionReceives the `ResizeObserverEntry` of `element`
optionsObserveResizeOptionsCancellation — see ObserveResizeOptions

function — A function that stops observing

The callback receives the ResizeObserverEntry of the element.

const stop = observeResize(canvas, (entry) => redraw(entry.contentRect));

Compose with debounce from helpers4/function instead of an option.

const stop = observeResize(frame, debounce(() => fitToViewport(), 100));

Options for observeResize.

interface ObserveResizeOptions {
  signal?: AbortSignalLike;
}

View source on GitHub