scroll-class.js is a small ES6 module that lets you toggle classes on elements when they appear in the viewport.
- ES6 ready
- No dependencies
- Performant and lightweight - 1.86 KB (unminified and no gzip)
$ yarn add scroll-class.jsimport ScrollClass from 'scroll-class.js';
const elements = [
{
element: document.querySelector('.your-element'),
classesToToggle: ['hello'],
once: true,
enabled: true,
events: true,
threshold: 100
}
];
new ScrollClass({
elements: elements,
frequency: 500
});
-
elements [array] (default: []): the array of objects with elements you want to check.element [DOM element]: element (DOM) you want to trackclassesToToggle [array]: class(es) you want to toggle on the given elementonce [bool]: only add the class onceenabled [bool]: this one explains itself.events [bool]: do you want events with that? See below for more info.threshold: [int]: threshold from top (without px postfix) - default is 0.
-
frequency [bool] (default: true): the amount of time between checks. (throttling - useful for performance)
Each element can also receive an insideViewport and outsideViewport event.
(use these before your new ScrollClass block if you don't want to miss the initial event)
document.querySelector('.your-element').addEventListener('insideViewport', function(){
console.log(`I see you! ${this}`);
});
document.querySelector('.your-element').addEventListener('outsideViewport', function(){
console.log(`I can't see you. ${this}`);
});
MIT
Free Software, Hell Yeah!