Home > Web Front-end > CSS Tutorial > How Can I Trigger CSS3 Animations Only When an Element Scrolls into View?

How Can I Trigger CSS3 Animations Only When an Element Scrolls into View?

Mary-Kate Olsen
Release: 2024-12-09 00:54:11
Original
742 people have browsed it

How Can I Trigger CSS3 Animations Only When an Element Scrolls into View?

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>
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);

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

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!

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