Home >Web Front-end >CSS Tutorial >How to Trigger CSS3 Animation Only When an Element is Scrolled into View?

How to Trigger CSS3 Animation Only When an Element is Scrolled into View?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 20:08:18524browse

How to Trigger CSS3 Animation Only When an Element is Scrolled into View?

Triggering CSS3 Animation on Scroll

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!

Statement:
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