Make Scroll Animations with ‘IntersectionObserver’


IntersectionObserver offers an efficient way to detect when elements enter or exit the view-port. We will use it to create animation when scrolling.


1. CSS

In the CSS part we need only two classes:

The first is an initial class that must be added to the elements which we want to apply the animation, and it is the beginning of the animation.

The second is the end of Animation.

2. IntersectionObserver

We utilize IntersectionObserver to detect the appearance of the element with the class “The-first-class”. Subsequently, a callback function is executed to change the element’s class from “The-first-class” to “The-second-class”.

Selection of “The-first-class”

Create IntersectionObserver

The IntersectionObserver constructor requires a callback function that switches between classes.

Create callback function

The callback function adds the class “The-second-class” to the element if element.isIntersecting is true; otherwise, it removes the class "The-second-class".

isIntersecting returns true if the element is in the view-port.

forEach is used to apply the callback function each observed element.

Excute the funtion

In this context, forEach is used to apply the callback function to all elements with the same class.

3. Media query

We use the prefers-reduced-motion media query to accommodate users who have requested the system to minimize the amount of non-essential motion it uses.

EXEMPLE LINK >>