Skip to main content

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.

NOTE

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​

import ScrollObserver from '@charmingdc/scrolljs';

Then, create a new instance of ScrollObserver:

const observer = new ScrollObserver();
Tip

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:

  1. animateOnce (Boolean)
  2. 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: observerOptions are totally optional, you can skip it when initializing ScrollObserver().
NAMETYPEDEFAULTMINMAXDESCRIPTION
rootElement OR browser viewportbrowser viewport~~The element that is used as the viewport for checking visibility.
thresholdnumber0.800.8Percentage of target’s visibility required to trigger the callback.
rootMarginstring-10px-80px80pxMargin around the root. Can be used to grow or shrink the root's bounding box.
Note

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',
});
NOTE

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​

  1. Import or include via CDN.
  2. Instantiate with optional animateOnce and observerOptions.

With these steps, you’ll have your ScrollObserver() class setuped and ready to use its method for adding scroll-triggered animations to your project 🎉