AshKeys

Confessions and Confusions of a Freelance Fullstacker.

Ashok Mannolu Arunachalam, How toCSSAnimation
Back

How to animate an element on scroll to view

You might have seen this type of animation happening in many of the sites you have visited and really wished to know do the same for yours.

Animating or performing a set of animations only when the user is scrolling to the view of a particular section or an element.

Intersection Observer API to the rescue

js
const elementToAnimate = document.querySelector(
'#sectionToAnimate'
);
const observer = new IntersectionObserver((entries, observer) => {
const [entry] = entries
const isOnscreen = entry.intersectionRatio > 0
if(isOnscreen) {
elementToAnimate.classList.add('animate-once');
observer.disconnect()
}
});
observer.observe(elementToAnimate);

IntersectionRatio is a range from 0 to 1 representing the percent the element visible in the view port. Sometimes you only want to trigger the animation when the element is partially visible to the user (or fully).

Do not forget to call disconnect() to stop observing the element or the callback will be invoked multiple times unless you want it that way ^_^