Problem:
An animated bar chart loads before content scrolls into view, resulting in missed animation.
Solution:
To activate the CSS3 animation upon scroll into view:
1. Capture Scroll Events
Implement JavaScript or jQuery event listeners that monitor scroll events.
2. Check for Element Visibility
For each scroll event, check if the element (bar chart) is visible in the user's viewport.
3. Start Animation
Once the element becomes visible (e.g., when isElementInViewport()) returns true), initiate the animation by applying the appropriate CSS class (e.g., "start").
Example Code:
<!-- HTML --> <div class="bar"> <div class="level eighty">80%</div> </div>
<!-- CSS --> .eighty.start { width: 0px; background: #aae0aa; -webkit-animation: eighty 2s ease-out forwards; -moz-animation: eighty 2s ease-out forwards; -ms-animation: eighty 2s ease-out forwards; -o-animation: eighty 2s ease-out forwards; animation: eighty 2s ease-out forwards; }
<!-- jQuery --> function isElementInViewport(elem) { // Calculate element and viewport positions // ... return ((elemTop < viewportBottom) && (elemBottom > viewportTop)); } function checkAnimation() { $elem = $('.bar .level'); // Prevent redundant animation start if ($elem.hasClass('start')) return; if (isElementInViewport($elem)) { // Start the animation $elem.addClass('start'); } } $(window).scroll(function(){ checkAnimation(); });
The above is the detailed content of How to Trigger CSS3 Animation Only When an Element is Scrolled into View?. For more information, please follow other related articles on the PHP Chinese website!