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

How Can I Activate CSS3 Animation Only When an Element Scrolls into View?

Linda Hamilton
Release: 2024-12-06 03:14:10
Original
644 people have browsed it

How Can I Activate CSS3 Animation Only When an Element Scrolls into View?

Activate CSS3 Animation When Content Scrolls into View

The query raises an issue where the animation for a bar chart activates upon page load, despite the chart being positioned off-screen. The goal is to trigger the animation only when the viewer scrolls down and the chart comes into view.

Capture Scroll Events

To achieve this, JavaScript or jQuery can be employed to monitor scroll events and determine when the element enters the viewport. Once detected, the animation can be initiated.

In the code below, JavaScript is used to add the "start" class to the element when it becomes visible, which triggers the animation:

<div class="bar">
    <div class="level eighty">80%</div>
</div>
Copy after login
.eighty.start {
    width: 0px;
    background: #aae0aa;
    animation: eighty 2s ease-out forwards;
}
Copy after login
function isElementInViewport(elem) {
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = $(scrollElem).scrollTop();
    var viewportBottom = viewportTop + $(window).height();
    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

By implementing this solution, the animation will only activate when the bar chart scrolls into view, providing a more engaging user experience.

The above is the detailed content of How Can I Activate CSS3 Animation 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