A small wrapper for IntersectionObserver that returns scroll information
npm i @imjasonmiller/scroll-io
import { ScrollIO } from '@imjasonmiller/scroll-io';
// Cache '.child' elements of '.selection'
const children = document.querySelectorAll('.selection .child');
const callback = ({ index, enterDown, leaveUp }, entry) => {
const ratio = entry.intersectionRatio;
if (enterDown || leaveUp) {
children[index].style.transform = `translateY(${50 * (1 - ratio)}%)`;
children[index].style.opacity = ratio;
}
};
const observer = new ScrollIO('.selection', callback, {
range: { steps: 50 },
});To apply a change in translateY and opacity based on how much of the image
is visible, one can use the ratio. Whether the image enters the viewport from
below or leaves it above is determined with enterDown and leaveUp
respectively.
const observer = new ScrollIO(selection,callback[, options]);| Default | Type |
|---|---|
null |
String | Element | NodeListOf<Element> |
String expects a selection string, e.g. .selection or #selection.
| Default | Type |
|---|---|
null |
Function |
Callback that is called on each intersection and receives the following arguments:
{
index: number,
enterUp: boolean,
enterDown: boolean,
leaveUp: boolean,
leaveDown: boolean,
},
entry: IntersectionObserverEntry,If needed, the index for each added Element allows you quick access, if
cached outside of the handler, preventing unnecessary querySelector calls.
An optional object which accepts the following properties:
| Default | Type |
|---|---|
{ min: 0, max: 1, steps: 0 } |
Object |
A wide range of intersection
thresholds
can be generated by changing steps. Passing 4 will generate: [0, 0.25, 0.5, 0.75, 1.0], as each step will be (max - min) / steps = 0.25.
If you would like to limit the range, set min or/and max.
If you want to pass a single threshold value, you only have to pass min.
IntersectionObserver.rootMargin, which allows one to offset the bounding box.
| Default | Type |
|---|---|
0px 0px 0px 0px |
string |
| Default | Type |
|---|---|
_scrollio |
String |
Each Element passed to selection will have a property attached to it in
order to store scroll related information. The default namespace can be
changed if desired.
Stops the observer.