Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/samthor/viz-observer
Notifies your code on DOM node move or resize
https://github.com/samthor/viz-observer
dom javascript
Last synced: 3 months ago
JSON representation
Notifies your code on DOM node move or resize
- Host: GitHub
- URL: https://github.com/samthor/viz-observer
- Owner: samthor
- License: apache-2.0
- Created: 2021-01-22T05:49:33.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2024-04-23T00:17:11.000Z (10 months ago)
- Last Synced: 2024-04-25T10:08:42.112Z (10 months ago)
- Topics: dom, javascript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/viz-observer
- Size: 23.4 KB
- Stars: 13
- Watchers: 5
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
This is an ES Module which exports the default method `vizObserver`.
It notifies you when an element is resized or moved on a page, including when it appears or disappears (similar to but _not quite_ being added/removed from the DOM).
See [this post](https://whistlr.info/2021/observing-dom/) for an explanation, or watch the animation:
![]()
## Usage
Install as "viz-observer".
```js
import vizObserver from 'viz-observer';const cleanup = vizObserver(yourElement, (rect) => {
console.info('element is now at', rect);
});// later
cleanup();
```This returns a cleanup method which you _must_ call when done, otherwise you risk memory leaks.
You can instead pass an `AbortSignal` as `{signal}` in the third argument:```js
const ac = new AbortController();vizObserver(yourElement, yourCallback, {signal: ac.signal});
// later
ac.abort();
```## Requirements
This requires `IntersectionObserver`, which [is pretty widely supported](https://caniuse.com/intersectionobserver).
It also requires `ResizeObserver` but this was released before `IntersectionObserver` in all browsers bar one.For Safari 12.x, which was the only browser to introduce `IntersectionObserver` _before_ `ResizeObserver`, it supports working in a slightly restricted mode: it won't report elements shrinking.
It'll only report elements when they grow, move or are removed/added from the page.## Notes
This works totally fine inside Shadow DOM.
It's how the author uses it: I report the location of interesting elements and "attach" unrelated elements to them, such as for a popup or tooltip.