How can I animate elements only when they are in the viewport using CSS3 and IntersectionObserver API?

DDD
Release: 2024-11-15 11:59:02
Original
904 people have browsed it

How can I animate elements only when they are in the viewport using CSS3 and IntersectionObserver API?

Animate Elements in Viewport

In CSS3, you can add animations to HTML elements to make them move or change appearance when certain conditions are met. However, if you want these animations to only play when the elements are visible in the viewport, you can use the IntersectionObserver API.

Using IntersectionObserver API

The IntersectionObserver API allows you to observe the intersection of elements with the viewport or an ancestor element. When an element becomes visible (i.e., intersects the viewport), you can trigger an action, such as toggling a class or executing an animation.

Here's an example implementation using IntersectionObserver:

const inViewport = (entries, observer) => {
  entries.forEach(entry => {
    entry.target.classList.toggle("is-inViewport", entry.isIntersecting);
  });
};

const Obs = new IntersectionObserver(inViewport);
const obsOptions = {}; //See: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Intersection_observer_options

// Attach observer to every [data-inviewport] element:
document.querySelectorAll('[data-inviewport]').forEach(el => {
  Obs.observe(el, obsOptions);
});
Copy after login

In the inViewport function, we check if the element is intersecting the viewport (i.e., entry.isIntersecting) and toggle a class is-inViewport on the target element.

To style the animation, you can use CSS transitions or keyframes as usual. For instance, you can define the animation for an element with data-inviewport="scale-in" as follows:

[data-inviewport="scale-in"] { 
  transition: 2s;
  transform: scale(0.1);
}

[data-inviewport="scale-in"].is-inViewport { 
  transform: scale(1);
}
Copy after login

With this setup, the element will scale from 10% to 100% when it becomes visible in the viewport.

The above is the detailed content of How can I animate elements only when they are in the viewport using CSS3 and IntersectionObserver API?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template