How to start css animation both when scrolling down and up

I use several CSS animations for the project. My problem is that these animations run only once when scrolling down. I need them to run every time the user scrolls them, regardless of whether it goes up or down the page.

CSS

.slideRight{

    animation-name: slideRight;
    -webkit-animation-name: slideRight; 

    animation-duration: 1.5s;   
    -webkit-animation-duration: 1.5s;

    animation-timing-function: ease-in-out; 
    -webkit-animation-timing-function: ease-in-out;     

    visibility: visible !important; 

}

@keyframes slideRight {

    0% {
        transform: translateX(-150%);
    }
    50%{
        transform: translateX(8%);
    }
    65%{
        transform: translateX(-4%);
    }
    80%{
        transform: translateX(4%);
    }
    95%{
        transform: translateX(-2%);
    }               
    100% {
        transform: translateX(0%);
    }   

}

@-webkit-keyframes slideRight {

    0% {
        -webkit-transform: translateX(-150%);
    }
    50%{
        -webkit-transform: translateX(8%);
    }
    65%{
        -webkit-transform: translateX(-4%);
    }
    80%{
        -webkit-transform: translateX(4%);
    }
    95%{
        -webkit-transform: translateX(-2%);
    }           
    100% {
        -webkit-transform: translateX(0%);
    }

}

HTML

<div class="animation-test element-to-hide" style="visibility:visible;">Something</div>

Javascript

$(window).scroll(function() {

    $('.animation-test').each(function(){

        var imagePos = $(this).offset().top;

        var topOfWindow = $(window).scrollTop();

        if (imagePos < topOfWindow+400) {
            $(this).addClass("slideRight");
        }

    });

});

$('.element-to-hide').css('visibility', 'hidden');

Jsfiddle

+4
source share
1 answer

Something like this should work.

Working example

$(window).scroll(function () {
    $('.animation-test').each(function () {
        var imagePos = $(this).offset().top;
        var imageHeight = $(this).height();
        var topOfWindow = $(window).scrollTop();

        if (imagePos < topOfWindow + imageHeight && imagePos + imageHeight > topOfWindow) {
            $(this).addClass("slideRight");
        } else {
            $(this).removeClass("slideRight");
        }
    });
});

Basically, it's just using an if statement to determine if an item is in the view port, and adding and removing a class. You can switch the visibility of an element using:

.element-to-hide{
    visibility:hidden; 
} 
.slideRight {
    visibility: visible;
    animation-name: slideRight;
    -webkit-animation-name: slideRight;
    animation-duration: 1.5s;
    -webkit-animation-duration: 1.5s;
    animation-timing-function: ease-in-out;
    -webkit-animation-timing-function: ease-in-out; 
}
+8

All Articles