Home  >  Article  >  Web Front-end  >  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
Susan SarandonOriginal
2024-11-17 06:05:04212browse

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

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

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!

Statement:
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