1

The following picks up the scrollTop value and adjusts css as expected:

      $(window).scroll(function() {
      if($window.scrollTop()>918){
        $menu.css({top:'0px'});
        }
      else{
        $menu.css({top:'80px'});
        }
      }

but the following (much nicer effect) doesnt. It fires seemingly intermittently when scroll event has finished

       $(window).scroll(function() {
       if($window.scrollTop()>918){
        $menu.animate({top:'0px'},100);
        }
      else{
        $menu.animate({top:'80px'},100);
        }
        }

Anyone any ideas why? so simple but driving me mental. Sure I am missing something, any help greatly appreciated

Mike Miller
  • 3,071
  • 3
  • 25
  • 32

1 Answers1

4

Because the scroll event fires many, many times while the user is moving the scroll bar and every time it fires you start up a new animation so you end up with a bunch of animations running at the same time that are all trying to move the menu differently.

It might work if you stopped the previous animation like this:

$(window).scroll(function() {
    if($window.scrollTop()>918){
        $menu.stop(true).animate({top:'0px'},100);
    } else {
        $menu.stop(true).animate({top:'80px'},100);
    }
}

But, it would probably work even better if you waited for the scroll operation to complete before doing the animation. See this post for a jQuery add-in method that waits for the scroll to complete.


EDIT: I had an even better idea. Start the animation on the first scroll move and allow it to just keep going unless the value changes:

$(window).scroll(function() {
    var menuTarget = $window.scrollTop()>918 ? "0px": "80px";
    // only do an animation if one isn't already going or
    // the current animation target is not what we want
    if (!$menu.is(":animated") || $menu.data("animTarget") !== menuTarget) {
        // set the new target, stop the current animation and start new animation
        $menu.data("animTarget", menuTarget)
            .stop(true).animate({top: menuTarget},100);
    }
}
Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Added a new option that only stops the current animation if it isn't the right animation target so if it is the right target, it will let the animation just keep running smoothly to completion with no jerkiness. – jfriend00 Oct 18 '12 at 21:26