The query raises an issue where the animation for a bar chart activates upon page load, despite the chart being positioned off-screen. The goal is to trigger the animation only when the viewer scrolls down and the chart comes into view.
To achieve this, JavaScript or jQuery can be employed to monitor scroll events and determine when the element enters the viewport. Once detected, the animation can be initiated.
In the code below, JavaScript is used to add the "start" class to the element when it becomes visible, which triggers the animation:
<div class="bar"> <div class="level eighty">80%</div> </div>
.eighty.start { width: 0px; background: #aae0aa; animation: eighty 2s ease-out forwards; }
function isElementInViewport(elem) { var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html'); var viewportTop = $(scrollElem).scrollTop(); var viewportBottom = viewportTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemTop < viewportBottom) && (elemBottom > viewportTop)); } function checkAnimation() { var $elem = $('.bar .level'); if ($elem.hasClass('start')) return; if (isElementInViewport($elem)) { $elem.addClass('start'); } } $(window).scroll(function(){ checkAnimation(); });
By implementing this solution, the animation will only activate when the bar chart scrolls into view, providing a more engaging user experience.
The above is the detailed content of How Can I Activate CSS3 Animation Only When an Element Scrolls into View?. For more information, please follow other related articles on the PHP Chinese website!