IntersectionObserver offers an efficient way to detect when elements enter or exit the view-port. We will use it to create animation when scrolling.
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.
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”.
The IntersectionObserver constructor requires a callback function that switches between classes.
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.
In this context, forEach is used to apply the callback function to all elements with the same class.
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.