Take the 2-minute tour ×

I'm using the following code to scroll a layer according to mouse position:


It works find however, I'm finding that the scroll speed is much faster when going to the right. Also noticed that if the scroller starts on the left and scroll to the right just a little bit and then scroll back tot he right again it's really really slow. I'm assuming that the actuall scroll speed isn't best controlled using the duration argument but I'm not sure how else to control the speed. I would like to have a consistent speed regardless of where the scroll bar is.

Any pointers?


share|improve this question
it should actually be scrollTop, not scrollTo. Typo? –  jAndy Jul 19 '10 at 14:09
sorry, well spotted. I'm actually using scrollLeft.. horizontal scroller... I've had a look at scrollTo plugin and smooth scroller but I'd like to avoid using loads of plugins... –  Steven Cheng Jul 19 '10 at 14:19
add comment

1 Answer

up vote 5 down vote accepted

The problem is that's a duration, not a speed you're passing, so you need to base the duration on the distance you need to move, like this:

$(".icons").each(function() {
  var duration = Math.abs($(this).scrollLeft() - x) * 2; //2ms per pixel moved
  $(this).animate({scrollLeft: x}, duration);

You can adjust that constant as needed, but that's the basic premise, get the distance you need to move (the absolute value) and multiply that number of pixels times some constant if needed, that's milliseconds per-pixel.

share|improve this answer
Thanks Nick, this is what I was after... still got to tweak my code abit but you've hit the nail on the head... cheers! –  Steven Cheng Jul 19 '10 at 14:37
just to update you that I've implemented the above and it works a treat. Much appreciated! –  Steven Cheng Jul 19 '10 at 15:55
@Steven - Excellent :) Always glad to hear an issue's solved. –  Nick Craver Jul 19 '10 at 16:07
Great, lean solution for a pretty common problem, thanks. –  markus Oct 12 '11 at 17:33
add comment

Your Answer


