Home > Web Front-end > CSS Tutorial > How to Trigger CSS3 Animations on Scroll into View?

How to Trigger CSS3 Animations on Scroll into View?

Linda Hamilton
Release: 2025-01-01 05:41:09
Original
171 people have browsed it

How to Trigger CSS3 Animations on Scroll into View?

How to Activate CSS3 Animation when Content Scrolls into View

Problem

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.

Solution: Capture Scroll Events

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.

Code Implementation

HTML

<div class="bar">
    <div class="level eighty">80%</div>
</div>
Copy after login

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;
}
Copy after login

jQuery

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();
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template