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