Skip to content

smithki/watch-resize

Repository files navigation

👀 watchResize

code style: airbnb code style: prettier

Watch any DOM element for size changes without polyfills.

💁🏼‍♂️ Introduction

A zero-dependency, cross-compatible ResizeObserver alternative that doesn't require polyfills. You can watch any element for size changes based on its bounding box.

🔗 Installation

Install via yarn or npm:

yarn add watch-resize
npm install watch-resize

🛠️ Usage

import { watchResize } from 'watch-resize';

const target = document.getElementById('my-element');

watchResize(target, ({ element, event, prevBoundingClientRect, destroy }) => {
  // Do stuff here for each "resize"
})).then(() => {
  // Once the promise resolves, the resize watcher has successfully mounted!
});

An object implementing ResizePayload is passed to subscribe handler:

export interface ResizePayload<T extends HTMLElement> {
  element: T;
  event: UIEvent;
  prevBoundingClientRect: ClientRect | DOMRect; // The previous result of "element.getBoundingClientRect()".
  destroy: () => void; // Unobserves the element and cleans up event listeners
}

About

Watch any DOM element for size changes without polyfills.

Resources

License

Stars

Watchers

Forks

Packages

No packages published