Initialization
After adding ScrollJs via CDN or package manager, you can start using it right away. The library exports a ScrollObserver class — just instantiate it to begin observing elements.
If you included ScrollJs via CDN, you don’t need to import: simply create a new instance of ScrollObserver() wherever you like.
1. Importing the ScrollObserver class
- ES Module
- CommonJS
import ScrollObserver from '@charmingdc/scrolljs';
const ScrollObserver = require('@charmingdc/scrolljs');
Then, create a new instance of ScrollObserver:
const observer = new ScrollObserver();
You can name the variable whatever you like, just make sure to assign the instance to a variable.
2. Configuration Options
You can customize ScrollObserver with two optional parameters:
- animateOnce (Boolean)
- observerOptions (Object)
2.1 animateOnce
- Type:
boolean - Default:
false - Description:
false→ Elements animate every time they enter the viewport.true→ Elements animate only once (the first time they become visible).
// Animate only once:
const observer = new ScrollObserver(true);
// Animate every time:
const observer = new ScrollObserver(false);
2.2 observerOptions
- Type:
Object - Default:
{ root: null, threshold: 0, rootMargin: '0px' } - Description:
observerOptionsare totally optional, you can skip it when initializingScrollObserver().
| NAME | TYPE | DEFAULT | MIN | MAX | DESCRIPTION |
|---|---|---|---|---|---|
root | Element OR browser viewport | browser viewport | ~ | ~ | The element that is used as the viewport for checking visibility. |
threshold | number | 0.8 | 0 | 0.8 | Percentage of target’s visibility required to trigger the callback. |
rootMargin | string | -10px | -80px | 80px | Margin around the root. Can be used to grow or shrink the root's bounding box. |
To set observerOptions, you must pass both parameters e.g., new ScrollObserver(animateOnceValue, observerOptions)
const container = document.querySelector('.my-custom-container');
const observer = new ScrollObserver(false, {
root: container,
threshold: 0.8,
rootMargin: '-10px',
});
When threshold is set to 0.8, rootMargin should stay within '-10px' to '10px' to ensure reliable animations.
If rootMargin reaches values like '-70px' or '70px', then threshold must not exceed 0.2 — otherwise, elements might fail to animate or appear on scroll.
3. Summary
- Import or include via CDN.
- Instantiate with optional
animateOnceandobserverOptions.
With these steps, you’ll have your ScrollObserver() class setuped and ready to use its method for adding scroll-triggered animations to your project 🎉