danyo
danyo

Reputation: 5846

window.scroll is not an instant animation

I am trying to detect when the user scrolls down on a page, so i can animate the height of a div. When the user is at the top of the page the #header is 100px, and once they scroll it becomes 50px. Here is my code:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 10) {
       $('#header').animate({height: "50px"});
    } else {
       $('#header').animate({height: "100px"});
    }
});

The above works, but when the user scrolls back to the top, there is a slight delay before the height animation happens.

Any ideas?

Upvotes: 0

Views: 336

Answers (2)

epascarello
epascarello

Reputation: 207521

window onscroll is called multiple times so you are triggering animate multiple times. This is causing multiple animations to be running at the same time. You need to cancel the previous animation with stop() before triggering the next.

$(window).scroll(function() {    
    var scrollTop = $(this).scrollTop();
    var height = (scrollTop >= 10) ? "50px" : "100px";
    $('#header').stop().animate({height: height});
});

Now another thing you can do is track the last height and if .is(':animated') is running, than do not bother calling it again. It would still require .stop()

Upvotes: 1

erikrunia
erikrunia

Reputation: 2383

I think the default duration is 400ms, maybe that is causing a visual delay. Have you tried NOT animating the height and just setting it via .css('height', '50px') instead?

at the very least that will tell you if its the animate() call causing the delay or the window.scroll event handler...

Upvotes: 1

Related Questions