scroll-triggers
A tiny, dependency-less javascript library to add classes as elements scroll into viewport.
Features
- Add a class when an element comes into view (great for animations)
- Set an image when an element comes into view (great for lazy loading)
- Set the width of an element based on scroll % (great for scroll progress bars)
- API for both HTML and Javascript
Install
npm install scroll-triggers
Setup
import 'scroll-triggers';
// alternative
import scrollTriggers from 'scroll-triggers';
Events
Custom events are fired/listened on the element:
Event | Type | Description |
---|---|---|
scrolltriggers:inView |
Fired | Element is in view |
scrolltriggers:outOfView |
Fired | Element is out of view |
scrolltriggers:pause |
Listened | Pauses scroll-triggers |
scrolltriggers:resume |
Listened | Resumes scroll-triggers |
Options
List of available options:
Usage
See the example.
HTML
Add class when element is in view.
<div data-scroll data-scroll-class="class-to-add"></div>
Add class when another element is in view
<div data-scroll data-scroll-class="class-to-add" data-scroll-start=".some .selector"></div>
Add class when another element is in view and remove when it gets to another element
<div data-scroll data-scroll-class="class-to-add" data-scroll-start=".some .selector" data-scroll-end=".some .lower .selector"></div>
Add class at when element hits bottom of page
<div data-scroll data-scroll-class="class-to-add" data-scroll-position="bottom"></div>
Add class at when element hits middle of page
<div data-scroll data-scroll-class="class-to-add" data-scroll-position="middle"></div>
Set an image when an element comes into view as a background image
<div data-scroll data-scroll-image="/path/to/image.jpg"></div>
<!--
This will generate the markup below:
<div data-scroll data-scroll-image="/path/to/image.jpg" style="background-image: url('/path/to/image.jpg'); background-repeat: no-repeat;"></div>
-->
Set the width of an element based on scroll % (great for progress bars)
<div data-scroll data-scroll-progress></div>
Set the src
property when an element comes into view (great for lazy load)
<iframe data-scroll data-scroll-src="https://wikipedia.org/wiki/Main_Page"/></iframe>
Set the srcset
property when an element comes into view (great for lazy load)
<picture>
<source media="(min-width: 650px)" data-scroll data-scroll-srcset="http://placehold.it/465x465?text=Min-650" />
</picture>
JavaScript
import scrollTriggers from 'scroll-triggers';
scrollTriggers([
{
el: '.some-selector',
start: '.selector',
end: '.selector',
className: 'class-to-add',
image: 'image/path.jpg',
src: 'http://url-to-resource.com',
srcSet: 'http://url-to-resource.com',
position: 'top|middle|bottom',
positionEnd: 'auto|top|middle|bottom',
offset: -20,
progress: true|false,
once: true|false,
fixed: true|false,
inView: (el, options) => {},
outOfView: (el, options) => {}
}
]);