You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
* modified the observer to fully leverage `IntersectionObserver`, now the `IntersectionObserverEntry` is the entry of our observer
* added 3 new options: `rootMargin`, `threshold` (for `IntersectionObserver`) and `callbackMode` (for `PositionObserver`)
* updated tests
* updated README
If you were looking for an observer that could replace all your `resize` and/or `scroll` EventListeners, this should be it! The **PositionObserver** works with the [IntersectionObserver API](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) under the hood and uses a very simple design.
10
9
11
-
The **PositionObserver** provides a way to asynchronously observe changes in the position of a target element with an ancestor element or with a top-level document's viewport. It tries to do what you would expect after your element has intersected as if you would listen to `resize` or `scroll` without attaching event listeners.
10
+
The **PositionObserver**is a lightweight utility that replaces traditional `resize` and `scroll` event listeners. Built on the [IntersectionObserver API](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver), it provides a way to asynchronously observe changes in the position of a target element with an ancestor element or with a top-level `document`'s viewport.
// when the position of the element changes from DOM manipulations and/or
68
-
// the position change was triggered by either scroll / resize events
69
-
// these will be the entries of this observer callback example
66
+
// Example callback entries
70
67
[{
71
-
// the observed target element
72
68
target: <div#myElement>,
73
-
// the target's bounding client react
74
-
boundingClientRect: DOMRect,
75
-
// parent <div#myModal> root clientWidth
76
-
clientWidth: number,
77
-
// root <div#myModal> clientHeight
78
-
clientHeight: number,
69
+
boundingClientRect: DOMRectReadOnly,
70
+
intersectionRatio: number,
71
+
isIntersecting: boolean,
72
+
// ... other IntersectionObserverEntry properties
79
73
}]
80
74
81
-
//anytime you need the entry, find it!!
82
-
observer.getEntry(target);
75
+
//Get an entry
76
+
observer.getEntry(myTarget);
83
77
84
-
//stop observing the changes for #myElement at any point
85
-
observer.unobserve(target);
78
+
//Stop observing a target
79
+
observer.unobserve(myTarget);
86
80
87
-
//anytime re-start observing the target
88
-
observer.observe(target);
81
+
//Resume observing
82
+
observer.observe(myTarget);
89
83
90
-
// when no targets require observation
91
-
// you should disconect the observer
92
-
observer.disconect();
84
+
// Stop all observation
85
+
observer.disconnect();
93
86
```
94
87
95
88
96
89
## Instance Options
97
90
98
-
### root: Element | undefined
99
-
Sets the `instance._root` private property which identifies the `Element` whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If not defined then the `Document.documentElement` will be used.
91
+
| Option | Type | Description |
92
+
|--------| -----|-------------|
93
+
|`root`|`Element`\|`undefined`| The element used as the viewport for checking target visibility. Defaults to `document.documentElement`.|
94
+
|`callbackMode`| "all" \| "intersecting" \| "update" \|`undefined`| Controls `PositionObserver` callback behavior. Defaults to "intersecting". See below for details. |
95
+
|`rootMargin`|`string`\|`undefined`| Margin around the root of the `IntersectionObserver`. Uses same format as CSS margins (e.g., "10px 20px"). |
96
+
|`threshold`|`number`\|`number[]`\|`undefined`| Percentage of the target's visibility required to trigger the `IntersectionObserver` callback. |
97
+
98
+
### root
99
+
The **PositionObserver**`instance.root` identifies the `Element` whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. Since we're observing for its width and height changes, this root can only be an instance of `Element`, so `Document` cannot be the root of your PositionObserver instance.
100
+
101
+
The **IntersectionObserver**`instance.root` is always the default, which is `Document`. The two observers really care for different things: one cares about intersection the other cares about position, which is why the two observers cannot use the same root.
102
+
103
+
### IntersectionObserver
104
+
The two initialization options specifically for the IntersectionObserver are `rootMargin` and `threshold` and only apply when using "intersecting" or "update" modes.
105
+
106
+
### Callback Modes
107
+
*`all`: Triggers the callback for all observed targets, regardless of visibility or position changes.
108
+
*`intersecting`: Triggers the callback only for targets that are intersecting with the document's viewport and have changed position or root dimensions.
109
+
*`update`: Triggers the callback for targets with position/root dimension changes or when a target's intersection status changes (e.g., from intersecting to non-intersecting).
100
110
101
-
When observing multiple targets from a **scrollable** parent element, that parent must be set as root. The same applies to embeddings and `IFrame`s. See the [ScrollSpy](https://github.com/thednp/bootstrap.native/blob/master/src/components/scrollspy.ts) example for implementation details.
111
+
When observing targets from a **scrollable** parent element, that parent must be set as root. The same applies to embeddings and `IFrame`s. See the [ScrollSpy](https://github.com/thednp/bootstrap.native/blob/master/src/components/scrollspy.ts) example for implementation details.
102
112
103
113
104
-
## How it works
105
-
* when the observer is initialized without a callback, it will throw an `Error`;
106
-
* if you call the `observe()` method without a valid `Element` target, it will throw an `Error`;
107
-
* if the target isn't attached to the DOM, it will not be added to the observer entries;
108
-
* once propertly set up, the **PositionObserver** will observe the changes of either **top** or **left** for a given Element target in relation to its designated root, as well as the **clientWidth** and **clientHeight** of that parent;
109
-
* when the target `Element` is intersecting with the bounds of the designated viewport and at least one of the observed values changes, only then the target's entry will be queued for the callback runtime.
114
+
## How it Works
115
+
***Initialization**: Requires a valid callback function, or it throws an Error.
116
+
***Target Validation**: The `observe()` method requires a valid `Element`, or it throws an Error. Targets not attached to the DOM are ignored.
117
+
***Observation**: Tracks changes in the target's top or left position relative to the root, as well as the root's `clientWidth` and `clientHeight`.
118
+
***Callback Trigger**: The callback is invoked based on the `callbackMode`:
119
+
-`all`: Includes every observed target's entry.
120
+
-`intersecting`: Includes only intersecting targets with position or root dimension changes.
121
+
-`update`: Includes targets with position/root dimension changes or a change in intersection status.
122
+
***Intersection Checks**: Uses `IntersectionObserver` with the `document` as the root to determine `isIntersecting`. The `rootMargin` and `threshold` options apply to these checks but have no impact in `all` mode.
110
123
111
124
112
125
## Notes
113
-
***use with caution**: for performance reasons, if your callback is focused on values of the target's bounding client rect, be sure to make use of `entry.boundingClientRect` values (`observer.getEntry(target)`) instead of invoking `getBoundingClientRect()` again on your target;
114
-
* this implementation is partially inspired by the [async-bounds](https://github.com/glued/async-bounds), the async model is very efficient;
115
-
* if nothing happens when observing a target, please know that the observer's runtime will only call the callback for elements that are descendents of the given root element; this also means that if a target is removed from the document, the target's entry will not be queued into the runtime;
116
-
* also if the target `Element` is hidden with either `display: none` or `visibility: hidden` or attributes with the same effect, the bounding box always has ZERO values and never changes, so make sure to have your target visible before calling `observer.observe(target)`;
117
-
* because the functionality is powered by `requestAnimationFrame` and **IntersectionObserver**, all computation is always processed asynchronously before the next paint, in some cases you might want to consider wrapping your **PositionObserver** callback in a `requestAnimationFrame()` invokation for a consistent syncronicity and to eliminate any [unwanted anomalies](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#observation_errors);
118
-
* while the performance benefits over the use of event listeners is undeniable, it's still **important** to `unobserve` targets or `disconnect` the observer to make room in the main thread;
119
-
* if you want to make your **PositionObserver** instance work like a `ResizeObserver`, well you can simply filter your callback with the inequality of `entry.boundingClientRect.height` and `lastHeight` OR `entry.boundingClientRect.width` and `lastWidth`;
120
-
* lastly, the **PositionObserver** will observe changes to all sides of a target, but in some cases you might want to narrow down to the changes triggered by scroll, mainly top and left, in which case you can filter your callback to a single side `entry.boundingClientRect.top !== lastTop`, further increasing performance.
126
+
***Performance**: Use `entry.boundingClientRect` from `observer.getEntry(target)` to avoid redundant `getBoundingClientRect()` calls.
127
+
***Async Design**: Leverages `requestAnimationFrame` and `IntersectionObserver` for efficient, asynchronous operation. Consider wrapping callbacks in `requestAnimationFrame` for synchronization and to eliminate any potential [observation errors](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#observation_errors).
128
+
***Visibility**: Targets must be visible (no `display: none` or `visibility: hidden`) for actual accurate bounding box measurements.
129
+
***Cleanup**: Call unobserve() or disconnect() when observation is no longer needed to free resources.
130
+
***ResizeObserver Alternative**: Filter callbacks on `entry.boundingClientRect.width` or height changes to mimic `ResizeObserver`.
131
+
***Scroll Optimization**: For scroll-specific changes, filter callbacks on `entry.boundingClientRect.top` or `left`.
132
+
***IntersectionObserver Root**: The underlying `IntersectionObserver` uses the `document` as its root, while `the PositionObserver`'s root option defines the reference `Element` for position tracking.
133
+
***Callback Mode Selection**: Choose `callbackMode` based on your use case:
134
+
- Use `intersecting` for most scenarios where only visible elements matter.
135
+
- Use `update` to track intersection state changes.
136
+
- Use `all` for comprehensive monitoring of *all* targets.
137
+
***RootMargin and Threshold**: These options have no impact in `all` mode, as non-intersecting targets are still processed. They are however relevant in `intersecting` or `update` modes for defining visibility conditions.
0 commit comments