How to Trigger CSS Animations When Elements Enter the Viewport During Page Scroll?

Barbara Streisand
Release: 2024-11-20 12:51:13
Original
417 people have browsed it

How to Trigger CSS Animations When Elements Enter the Viewport During Page Scroll?

Animating Elements When Visible in Viewport During Page Scroll

When using CSS animations on a web page, it's common to encounter situations where all animations play simultaneously, obscuring those at the bottom. To address this issue, we'll explore a solution using IntersectionObserver API.

IntersectionObserver API

The IntersectionObserver API allows developers to monitor changes in an element's intersection with its parent container or the viewport. When an element comes into view, it triggers an event that can be used to initiate actions.

Example Implementation

Here's an example that triggers CSS class toggle when an element becomes visible in the viewport:

<br>const inViewport = (entries, observer) => {<br>  entries.forEach(entry => {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">entry.target.classList.toggle("is-inViewport", entry.isIntersecting);
Copy after login

});
};

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);
});

In the above example, all elements with the [data-inviewport] attribute will be monitored. When an element is in view, the is-inViewport class is added, and the animation defined in the CSS below will trigger.

<br>[data-inviewport="scale-in"] { <br>  transition: 2s;<br>  transform: scale(0.1);<br>}<br>[data-inviewport="scale-in"].is-inViewport { <br>  transform: scale(1);<br>}</p>
<p>[data-inviewport="fade-rotate"] { <br>  transition: 2s;<br>  opacity: 0;<br>}<br>[data-inviewport="fade-rotate"].is-inViewport { <br>  transform: rotate(180deg);<br>  opacity: 1;<br>}<br>

This solution ensures that animations only play when elements become visible during scrolling, improving the user experience and creating a more visually appealing web page.

The above is the detailed content of How to Trigger CSS Animations When Elements Enter the Viewport During Page Scroll?. 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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template