Activating CSS3 Animation When Content Scrolls into View
When an element's position goes beyond the viewport, it becomes hidden from view. To optimize performance, CSS3 animations can be initiated only when an element appears within the viewport. This is especially useful for elements placed far down a page with substantial content above them.
To achieve this, we utilize JavaScript or jQuery for capturing scroll events. Once a scroll event is triggered, the code checks whether the targeted element has scrolled into the viewport. If so, an indication class is added to the element, prompting the animation to commence.
Code Implementation:
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) { var $elem = $(elem); // Scroll position var viewportTop = $(window).scrollTop(); var viewportBottom = viewportTop + $(window).height(); // Element position 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(); });
The above is the detailed content of How Can I Trigger CSS3 Animations Only When an Element Scrolls into View?. For more information, please follow other related articles on the PHP Chinese website!