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 for an explanation, or watch the animation:
Install as "viz-observer".
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:
const ac = new AbortController();
vizObserver(yourElement, yourCallback, {signal: ac.signal});
// later
ac.abort();
This requires IntersectionObserver
, which is pretty widely supported.
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.
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.