A performant scroll observer without event listeners.
Based on IntersectionObserver API. Injects invisible marks in the DOM and triggers user defined callbacks.
import ScrollObserver from "./ScrollObserver.js";
const scrollObserver = new ScrollObserver({
thresholds: "0.25",
triggerOnce: true,
triggerPrevious: true,
});
scrollObserver.observe([25, 50], (depth) => {
// do something
});
scrollObserver.observe(75, (depth) => {
// do something
});target
default: document.body
description: root element to monitor when scrolling
rootMargin
default: '0px 0px 0px 0px'
description: sets the area margin when to trigger the thresholds, positive values shifts the detection area outside the screen to trigger callbacks earlier before they enter the viewport
showRootMargin
description: shows rootMargin areas when thresholds should trigger, may be not visible when it's outside the viewport
thresholds
default: [0, 0.25, 0.5, 0.75, 1]
description: These are the measure points, they will trigger the callbacks when the threshold entered the viewport. They represent percentages. Can be an array of values:
[0, 10, 25, 45, 50, 70, 100] or [0, 0.10, 0.25, 0.45, 0.50, 0.70, 1]
Can be automatically generated by providing a step as string:
'0.25' => [0, 0.25, 0.50, 0.75, 1]
interactWhen
default: 0
description: Tiggers only callbacks from this threshold and above, ignores the callbacks below this mark. Expects an percentage number.
excludeZero
default: false
description: does not trigger on 0 scroll depth
triggerOnce
default: false
description: triggers registered callbacks only once when the threshold was passed
triggerPrevious
default: false
description: triggers registered callbacks on pageload when they are already below the current scroll depth
| Option | Default | Description |
|---|---|---|
| showMarkers | false | display horizontal lines where the markers are located |
| markerClasses | 'sc-scroll-depth-marker' | set classes on markers, separated by space |
| markerIdPrefix | '' | set IDs for markers as a prefix followed by a number |
| scrollWrapperId | 'sc-scroll-wrapper' | set ID for the wrapper element |