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
Release: 2024-11-30 20:08:18
Original
458 people have browsed it

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

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!

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