Plain vanilla JS IntersectionObserver utility, to be used as a mixin.
$ npm install intersection-observer-js
You just need to import the utility and then instantiate it with an object:
import inViewport from 'intersection-observer-js';
const sections = document.querySelectorAll(".section");
inViewport({
$elements: sections,
});
A more complex example would be using special callback and data attribute (see below for API):
import inViewport from 'intersection-observer-js';
const sections = document.querySelectorAll(".section");
inViewport({
$elements: sections,
inCallback: (entry) => {
console.log('intersection crossed at', entry.intersectionRatio);
},
dataPos: 'data-intersection-state',
});
Object being passed to inViewport
has the following attributes.
### $elements
A Nodelist of elements must be provided. These are the elements being observed.
@type {Nodelist}
@required
### observerOptions
The options object passed into the IntersectionObserver() constructor, as per API definition. If not specified it takes the defaults.
@type {Object}
Optional callback to be run at the startHook
(beginning of an intersection change).
@type {Function}
Optional callback to be run at the inHook
(intersection entry).
@type {Function}
Optional callback to be run at the outHook
(intersection exit).
@type {Function}
Optional callback to be run at the endHook
(end of an intersection change).
@type {Function}
Optional string being used to store the position changes.
@type {String}
@default 'data-in-viewport-position'
Optional string being used as the position value when entry.isIntersecting
.
@type {String}
@default 'intersecting'
Optional string being used as the position value when element being observed is above the definded intersection.
@type {String}
@default 'above'
Optional string being used as the position value when element being observed is below the definded intersection.
@type {String}
@default 'below'
Optional string being used to store the direction changes.
@type {String}
@default 'data-in-viewport-direction'
Please note this data attribute is only being set when entry.isIntersecting
, and value is built prepending from-
string to either txtAbove
or txtBelow
.
The order of execution of default and hooked events is as follows:
startHook
- Internal update of direction data attribute
- Internal update of position data attribute
-
inHook
/outHook
endHook
MIT