fold-notifier
Deal with the dom elements who enter the viewport
Install
npm i fold-notifier
Package on npm
API
constructor(cb, [opts])
Argument | Action |
---|---|
cb | the callback |
opts.attribute | optional targeted attribute, default to fold |
opts.offset | optional offset, default to 0 |
opts.target | optional targeted container, default to document.body |
The callback cb
receive 2 arguments
Argument | Action |
---|---|
el | the dom element entering the viewport |
data | a Plain Object with serialized attribute values |
You must call add
or collect
to start
add(arg, [arg], [...])
Add new elements manually
arg
can be:
- a Html Element
- a NodeList
- a flat Array or an Array of nested
arg
Make sure that the array contains valid node elements with the correct opts.attribute
The elements are directly added in the previous internal data storage, faster than the collect method
const Fold = var fold = /* ... */ var ela = documentvar elb = documentvar elc = documentvar lst = document fold
collect()
Collect new elements where opts.attribute
is found
Use it when interesting new nodes are appended to the dom
Elements already "done" are ignored
It reset the internal data storage. Every element not "done" are tested / imported again
Safer than the add method with the opts.attribute
test, but slower
Return the count of watched elements
Return the count of watched elements
<!-- .one and .two are ignored --> <!-- .three is collected -->
kill()
Stop and delete all internal stuffs. Nothing can be done after that
Example 1
Two div will be animated when they enter the viewport
/* animation starts when the attribute `fold-done` is setted */
const Fold = // when update is invoked, the attribute `fold-done` was just setted to `el` { // `el` with class `.two` receive serialized data {offset:-25, delay:-1.3} if datadelay != null elstyletransitionDelay = datadelay + 's' } var fold = update offset: -25fold
Example 2
Images are lazyloaded when they are about to enter the viewport
<!-- b.gif is the famous 1x1 transparent pixel image -->
const Fold = // when update is invoked, the attribute `lazy-done` was just setted to `el` { // `el` with class `.one` receive serialized data {offset:250, src:'image1.jpg'} // `el` with class `.two` receive {offset:250, src:'image2.jpg'} if datasrc != null elsrc = datasrc } var fold = update offset: 250 attribute:'lazy'fold
License
MIT