How to Animate Elements Only When They\'re in Viewport?

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

How to Animate Elements Only When They're in Viewport?

Animating Elements in Viewport Using Page Scroll

Q: How can I display animations on a webpage only when the elements are visible in the viewport while scrolling?

A: To achieve this, you can utilize the IntersectionObserver API.

Intersection Observer API

The Intersection Observer API allows you to observe the intersection between an element and its parent element or the viewport. It enables you to trigger events based on whether the element is visible within the viewport.

Here's an example using the API to toggle a class that can be used to trigger animations:

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

const Obs = new IntersectionObserver(inViewport);
const obsOptions = {};

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

You can then add CSS transitions or animations to the elements with the "is-inViewport" class to animate them when they appear in the viewport. For example:

[data-inviewport] {
  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

With this code, elements with the [data-inviewport] attribute will have a CSS transition. When they enter the viewport, the is-inViewport class will be added to trigger the animation.

The above is the detailed content of How to Animate Elements Only When They\'re in Viewport?. 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