You're using CSS3 animations to bring a bar chart to life, but the animation starts the moment the page loads. As the bar chart is placed off-screen due to preceding content, the animation is complete by the time users scroll down to view it.
The key lies in capturing scroll events using JavaScript or jQuery. With each scroll, the code will check if the bar chart element is within the viewport. Once it detects the element's visibility, it triggers the animation by adding a "start" class that initiates the animation.
<div class="bar"> <div class="level eighty">80%</div> </div>
.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; }
function isElementInViewport(elem) { var $elem = $(elem); // Get scroll position var viewportTop = $(scrollElem).scrollTop(); var viewportBottom = viewportTop + $(window).height(); // Get element position var elemTop = Math.round( $elem.offset().top ); var elemBottom = elemTop + $elem.height(); return ((elemTop < viewportBottom) && (elemBottom > viewportTop)); } function checkAnimation() { var $elem = $('.bar .level'); // Prevent re-animation if ($elem.hasClass('start')) return; if (isElementInViewport($elem)) { $elem.addClass('start'); } } // Capture scroll events $(window).scroll(function(){ checkAnimation(); });
The above is the detailed content of How to Trigger CSS3 Animations on Scroll into View?. For more information, please follow other related articles on the PHP Chinese website!