Home > Web Front-end > CSS Tutorial > How Can I Animate Elements Only When They Enter the Viewport on Page Scroll?

How Can I Animate Elements Only When They Enter the Viewport on Page Scroll?

Susan Sarandon
Release: 2024-11-17 06:05:04
Original
289 people have browsed it

How Can I Animate Elements Only When They Enter the Viewport on Page Scroll?

Animating Elements in Viewport on Page Scroll

In a webpage with multiple animated elements, it can be challenging to control when these animations start. To achieve smooth scrolling animations, we need a way to trigger them only when their respective elements come into view. Here's how you can achieve that using the IntersectionObserver API.

Using IntersectionObserver API

The IntersectionObserver API monitors the visibility of elements in relation to the viewport or a specified parent element. We can use this to toggle CSS animations when an element becomes visible.

Code Snippet

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

CSS Animation Example

Here's an example of how to apply animations to elements that are in view:

[data-inviewport] { /* THIS DEMO ONLY */
  width:100px; height:100px; background:#0bf; margin: 150vh 0; 
}

/* inViewport */

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

[data-inviewport="fade-rotate"] { 
  transition: 2s;
  opacity: 0;
}
[data-inviewport="fade-rotate"].is-inViewport { 
  transform: rotate(180deg);
  opacity: 1;
}
Copy after login

Conclusion

By leveraging the IntersectionObserver API, we can now control the timing of our animations, ensuring they play when the corresponding elements become visible in the viewport. This approach provides a seamless and engaging experience for users as they scroll through your webpage.

The above is the detailed content of How Can I Animate Elements Only When They Enter the Viewport on 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template