Scroll Animation using Intersection Observer API

,

|

|

|

5 minutes

If you want to make your web page more engaging and interactive, you might want to consider adding some animations to your elements. Animations can create a sense of motion, excitement, and surprise for your visitors, and make your page stand out from the rest. But how can you implement animations without using any external libraries or frameworks? The answer is the JavaScript Intersection Observer API.

What is the Intersection Observer API?

The JavaScript Intersection Observer API is a feature that allows you to detect when an element in the DOM becomes visible or hidden in the viewport. The viewport is the part of the browser window that shows the web page content. You can use this feature to perform tasks such as lazy loading images, infinite scrolling, animating elements on scroll, or tracking ad impressions.

How to Use Intersection Observer API?

To use the JavaScript Intersection Observer API, you need to follow these steps:

  1. Create an intersection observer object. This is a class that takes a callback function and some options as parameters. The callback function will be executed whenever the visibility of an element changes according to the options. The options include:
    • root: The element that acts as the viewport for checking visibility. If not specified, the browser’s viewport is used.
    • rootMargin: A string that specifies the margins around the root element. The margins are added or subtracted from the root element’s bounding box when calculating intersections. The string can have values similar to the CSS margin property, such as “10px 20px 30px 40px”.
    • threshold: A number or an array of numbers between 0 and 1 that indicates at what percentage of the element’s visibility the callback function should be executed. For example, if you want to detect when the element is 50% visible, you can use a value of 0.5.
  2. Select the elements that you want to observe. You can use any selector method, such as querySelectorAll(), to get a collection of elements that you want to monitor for visibility changes.
  3. Start observing the elements. You can use the observe() method of the intersection observer object to pass each element that you want to observe. The intersection observer object will then start monitoring their visibility and position relative to the root element or the viewport.
  4. Stop observing the elements. You can use the unobserve() method of the intersection observer object to stop observing an element. This will remove it from the list of observed elements and stop invoking the callback function for it.

To know more read MDN: Intersection Observer API

Scroll Animation Using Intersection Observer API

In this article, we will show you how to use the JavaScript Intersection Observer API to animate elements on scroll. We will use a simple example where we have some elements that have a data-attribute called “data-animation”. This attribute specifies the name of the animation class that we want to apply to the element when it becomes visible in the viewport. We will use some CSS animation classes from [Animate.css], a library that provides ready-to-use animations for web elements.

Here is our HTML code:

<main>
	<section>
		<div>
			<h3>This is Heading</h3>
			<br />
			<div class="animation-group">
				<div data-animation="fadeInLeft"><span class="icon">🙈</span><span class="text">Animation</span></div>
				<div data-animation="fadeInLeft"><span class="icon">🙉</span><span class="text">Animation</span></div>
				<div data-animation="fadeInLeft"><span class="icon">🙊</span><span class="text">Animation</span></div>
				<div data-animation="fadeInLeft"><span class="icon">🐵</span><span class="text">Animation</span></div>
			</div>
		</div>
	</section>
	.....
	.....
</main>

Here is our JS code:

const animatedEls = document.querySelectorAll("[data-animation]");

const observer = new IntersectionObserver((entries) => {
	entries.forEach((entry) => {
		const animation = entry.target.getAttribute("data-animation");

		if (entry.isIntersecting) {
			entry.target.classList.add("animated", `${animation}`);
		} else {
			entry.target.classList.remove("animated", `${animation}`);
		}
	});
});

animatedEls.forEach((el) => observer.observe(el));

🕹 CSS is a bit long so you can check this codepen demo: https://codepen.io/iamsaief/pen/qBYPdGx

Let see what this code does:

  • It selects all elements that have a data-attribute called “data-animation”.
  • It creates a callback function that handles the intersection events.
  • It loops through each entry, which is an object that contains information about the intersection state of each element.
  • It gets the value of the “data-animation” attribute and stores it in a variable called “animation”.
  • It checks if the entry is intersecting, which means that the element is at least partially visible in the viewport.
  • If it is, it adds two classes to the element: “animated” and the value of “animation”. These classes will trigger the animation effect defined in the Animate.css library.
  • If it is not, it removes these classes from the element, which will stop or reverse the animation effect.
  • It creates an intersection observer object and passes it the callback function and some options. The options are not specified, so the default values are used.
  • It starts observing each element using the observe() method of the intersection observer object.

Now you can watch the demo video again and hope you’ll understand what is going on to the screen. See the live demo: https://codepen.io/iamsaief/full/

As you can see, using the JavaScript Intersection Observer API is a simple and powerful way to animate elements on scroll. You can use any CSS animation library or create your own animations to make your web page more dynamic and fun. You can also use this feature for other purposes, such as lazy loading images, infinite scrolling, or tracking ad impressions. The possibilities are endless!

I hope you enjoyed this article and learned something new.

Happy Coding, Cheers 🥂