CSS Animations: Pause When Element Is Hidden and Improve the Performance

CSS Animations: Pause When Element Is Hidden and Improve the Performance

CSS animations can bring life to your web pages, making them more engaging and interactive. However, running animations continuously, especially when elements are not in the viewport, can be a waste of resources and can impact performance. In this blog post, we’ll learn how to pause CSS animations when an element is hidden (i.e., out of the viewport) using the Intersection Observer API, and how this can help improve performance.

Why Pause Animations?

When an element is not visible on the screen, running its animation is unnecessary and can lead to:

  • Increased CPU Usage: Animations consume CPU resources, which can slow down the browser and degrade the user experience.
  • Battery Drain: For mobile users, unnecessary animations can drain the battery faster.
  • Poor Performance: Overall performance of your web page can be negatively impacted, especially if there are multiple animated elements.

Using the Intersection Observer API

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport. This makes it a perfect tool for our task.

Step-by-Step Guide

Let’s dive into the implementation.

1. HTML Structure

First, ensure you have an element with the animation you want to control.

<div class="animated-element">
  <!-- Your content here -->
</div>

2. CSS Animation

Define the CSS animation.

.animated-element {
  animation: myAnimation 3s infinite;
}

@keyframes myAnimation {
  0% { transform: translateX(0); }
  100% { transform: translateX(100px); }
}

.paused {
  animation-play-state: paused;
}

3. JavaScript to Control the Animation

Use the Intersection Observer API to detect when the element is in or out of the viewport and toggle the animation state accordingly.

document.addEventListener("DOMContentLoaded", () => {
  const animatedElement = document.querySelector('.animated-element');

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        animatedElement.classList.remove('paused');
      } else {
        animatedElement.classList.add('paused');
      }
    });
  });

  observer.observe(animatedElement);
});

Explanation

  1. HTML: A div with the class animated-element represents the component you want to animate.
  2. CSS:
    • .animated-element defines the animation.
    • .paused sets the animation-play-state to paused, effectively stopping the animation when applied.
  3. JavaScript:
    • An IntersectionObserver is created to observe the .animated-element.
    • When the element intersects (i.e., is visible in the viewport), the paused class is removed, allowing the animation to play.
    • When the element does not intersect (i.e., is out of the viewport), the paused class is added, pausing the animation.

Conclusion

By using the Intersection Observer API, we can efficiently manage CSS animations, ensuring they only run when necessary. This simple yet effective technique can significantly improve the performance of your web pages, providing a smoother and more enjoyable experience for your users.

Give it a try on your projects and see the difference it makes! Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *