13

I am using this code to scroll to a certain element on my page:

$("html, body").animate({scrollTop: $(".myDiv").offset().top}, 300);

It works, but there is one issue with it: When the user scrolls down while the script scrolls up, there is some juddering because there are two scroll commands at the same time in different directions - sounds logical to me.

I checked some other sites with such scroll functionality, there is no juddering. So what's the trick to prevent this?

Community
  • 1
  • 1
Sven
  • 12,129
  • 25
  • 82
  • 140

2 Answers2

13

Thats a jQuery bug when you use animate with scrolling, good detection.

I did a research how to turn it off scrolling and find this question : How to disable scrolling temporarily?

Here is jsFiddle. You will see after click; user cant scroll untill animate complete.

$('.myDiv').click(function(){

    disable_scroll();

    $('html, body').stop().animate({ scrollTop: 0 }, 700,function() {
        enable_scroll();
    });
});

edit: thanks to galambalazs btw.

Community
  • 1
  • 1
Barlas Apaydin
  • 6,794
  • 10
  • 50
  • 81
  • 1
    Thanks for pointing me to galambalazs' answer. If anyone else ends up here, I've refactored his solution into a nice self-contained object: http://stackoverflow.com/a/21533631/940252 – Josh Harrison Feb 03 '14 at 17:27
0

an idea - try hooking to the scroll event and use http://api.jquery.com/stop/ to stop your animation .. bad idea..

same problem with a solution - let user scrolling stop jquery animation of scrolltop?

Community
  • 1
  • 1
Avi Pinto
  • 4,086
  • 2
  • 22
  • 21