Why run the animation if the user can’t enjoy it?

(This is the sequel post of https://justanotherwebdev.com/posts/intersection-observer-part-1/ )

As soon as you learn css animation, you eager to add a lot of animations in your website. So do I.

Let’s take a step back and think about it, we do cool animations with animation to showcase our skills but what is the point if the animation is already finished and user can’t even see and enjoy it?

Let’s take a look at this starter codepen again, shall we?

In here, I added slideInFromLeft animation to the images to slide in. After 1 second, the animation is already finished and user can’t even see the full animation or no animation at all based on the time that they scrolled.

In this case, we can also use intersectionObserver to run the animation only if the section is in the sight of user.

1) Let’s update the css a little bit.

.img-container.active {  
  /* This section calls the slideInFromLeft animation we defined above */
  animation: 1s ease-out 0s 1 slideInFromLeft;
}

Update the css code to include .active. (It is the custom class name, you can even named .banana or .potato

2) Let use the intersectionObserver again. You can just copy the previous code from the previous post and just change image.src = imageURL; to image.classList.add('active');

OOPS! my bad, you need update to documentQuerySelectorAll to .img-container also as we add our cool css animation class in there.

const images = document.querySelectorAll('.img-container');

// Loop through the images 
images.forEach(image => {
	const observer = new IntersectionObserver((entries, observer) => {
			entries.forEach(entry => {
					if (entry.isIntersecting) {
							// Change the image src to imageURL
							image.classList.add('active');
					}
			});
	}, {});

	observer.observe(image); 
})

Congrats my comrades! Now you got the animation and you also make sure that user can enjoy it.

As usual, here is the final codepen for you to take a reference.

https://codepen.io/starryskadi/pen/NWmGxdW

Happy Hacking!

Copyright © 2024, JUST ANOTHER WEB DEV.