Kater89
Kater89

Reputation: 93

ScrollTop has hesitation when returning to top

I am trying to change css styles as a user scrolls down and set them back to how they were when the user scrolls back to the top.

$(window).on( 'scroll', function(){
    if ($(window).scrollTop() > 0) {
        $('#mainMenu').animate({marginTop: '15px'},300);
        $('#phoneNumber').animate({opacity: '0'},300);
        $('#mainNav').addClass("mainNavScroll");
    } else {
        $('#mainMenu').animate({marginTop: '70px'},300);
        $('#phoneNumber').animate({opacity: '1'},300);
        $('#mainNav').removeClass("mainNavScroll");
    }
});

It does the top part of the code (the first "if" section) fine but when I scroll back up to the top, I have problems with the "else" code. It does the last line right away (removes .mainNavScroll from #mainNav) and then waits about a minute to do the rest of the code (animations for #mainMenu and #phoneNumber).

Upvotes: 2

Views: 79

Answers (1)

Smern
Smern

Reputation: 19066

I think this is what you want:

var top = true;
$(window).on( 'scroll', function(){
    if ($(window).scrollTop() > 0) {
        if (top) {
            top = false;
            $('#mainMenu').stop().animate({marginTop: '15px'},300);
            $('#phoneNumber').stop().animate({opacity: '0'},300);
            $('#mainNav').stop().addClass("mainNavScroll");
        }
    } else if (!top) {
        top = true;
        $('#mainMenu').animate({marginTop: '70px'},300);
        $('#phoneNumber').animate({opacity: '1'},300);
        $('#mainNav').removeClass("mainNavScroll");
    }
});

The .stop()'s will stop any animation that is currently running before running the next. This will prevent queues where animations wait for each other.

The top var is to prevent the non-top animations from being triggered thousands of times while scrolling.

If you want the class added/removed after the animations are complete, you can use a callback like this:

$('#mainMenu').animate({marginTop: '70px'},300, function() {
    $('#mainNav').removeClass("mainNavScroll");
});

Upvotes: 1

Related Questions