Nabil Ghulam
Nabil Ghulam

Reputation: 211

jQuery: Something is delaying animations

What makes the animation delay? All jQuery on the site is having some sort of delay..

$(function(){
  $(window).scroll(function() {
       var elementTop = $('body').offset().top; 
       var position = elementTop+ $(window).scrollTop();
       if(position >= 20){
           $('#top').animate({top: '40px'}, 300);
       } else if(position < 20){
           $('#top').animate({top: '80px'}, 300);
       }
console.log(position);
  });   
});

Live: Link here - It's the menu/navigation

Upvotes: 0

Views: 67

Answers (1)

Ast Derek
Ast Derek

Reputation: 2729

Your code is being fired each time you scroll. The animate methods are being concatenated, running one after the other. To achieve what you want, you need to stop the current animation and start a new one:

$(function(){
    $(window).scroll(function(){
        var elementTop = $('body').offset().top,
        position = elementTop+ $(window).scrollTop();

        if (position >= 20){
            $('#top').stop().animate({top: '40px'}, 300);
        }
        else if (position < 20) {
           $('#top').stop().animate({top: '80px'}, 300);
        }
    });   
});

Upvotes: 5

Related Questions