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