Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding different CSS animations on scroll up and scroll down with jQuery

I'm trying to add classes when the user scrolls up and down in order to show 2 css animations.

It works well if I'm only using the scroll down animation, but its inconsistent when I use both the scroll up and scroll down animations.

I'm having problems getting animations to fire multiple times in a row. As in- scroll down pause, scroll down pause, scroll up pause, scroll up pause.

Here's a jsFiddle to better demonstrate the problem.

and the code-

(function () {
    var previousScroll = 0;

    $(window).scroll(function () {
        var currentScroll = $(this).scrollTop();
        if (currentScroll > previousScroll) {
            //down scroll code
            $("#repel").removeClass("climb");
            $("#repel").addClass("repel").delay(1150).queue(function (next) {
                $(this).removeClass("repel");
                next();
            });
        } else {
            // upscroll code
            $("#repel").removeClass("repel");
            $("#repel").addClass("climb").delay(1000).queue(function (next) {
                $(this).removeClass("climb");
                next();
            });
        }
        previousScroll = currentScroll;
    });
}());
like image 988
apaul Avatar asked Apr 15 '26 06:04

apaul


1 Answers

I figured it out...

I just needed to change the way the animations were being removed. Rather than using a delay and queue I detected the animation end and removed it that way.

Working Example

(function () {
    var previousScroll = 0;

    $(window).scroll(function () {
        var currentScroll = $(this).scrollTop();
        if (currentScroll > previousScroll) {
            //down scroll code
            $("#repel").addClass("repel");
            $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function () {
                $('#repel').removeClass('repel');
            });

        } else {
            // upscroll code
            $("#repel").addClass("climb");
            $("#repel").on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function () {
                $('#repel').removeClass('climb');
            });
        }
        previousScroll = currentScroll;
    });
}());
like image 186
apaul Avatar answered Apr 16 '26 23:04

apaul