watch-resize

Watch any DOM element for size changes without polyfills.

Usage no npm install needed!

<script type="module">
  import watchResize from 'https://cdn.skypack.dev/watch-resize';
</script>

README

👀 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
}