Fix jolts when using jQuery scrollTop

I have a function that scrolls to the next section of the article when the down arrow on the keyboard is pressed and scrolls when the up arrow is pressed. It works fine, but there is a slight β€œbounce” or β€œshiver” before scrolling.

I was able to partially fix this problem if the function returns false, however returning false swallows the event with the key pressed, preventing my keyboard from interacting with the browser.

Any ideas on how to eliminate jitter and release the keyboard at the same time?

var $sections = $('.section'); var curr = -1; $(document).keydown(function(e){ prev = (curr < 0)? $sections.length-1: curr-1; next = (curr >= $sections.length-1)? -1: curr+1 ; switch (e.keyCode) { case 38: // up key s = $sections.eq(prev).offset().top; curr = prev; break; case 40: // down key s = $sections.eq(next).offset().top; curr = next; break; default: break; } if (curr == -1 ){ $('html, body').animate({scrollTop: 0}, 'slow'); } else{ $('html, body').animate({scrollTop: s}, 'slow'); } return e; }); 
+4
source share
2 answers

Thanks Yi ... as an alternative ... I just got it to work, setting a default switch case to return e. Then returning at the bottom of the function returns false.

The result looks something like this:

 var $sections = $('.section'); var curr = -1; $(document).keydown(function(e){ prev = (curr < 0)? $sections.length-1: curr-1; next = (curr >= $sections.length-1)? -1: curr+1 ; switch (e.keyCode) { case 38: // up key s = $sections.eq(prev).offset().top; curr = prev; break; case 40: // down key s = $sections.eq(next).offset().top; curr = next; break; default: return e; } if (curr == -1 ){ $('html, body').animate({scrollTop: 0}, 'slow'); } else{ $('html, body').animate({scrollTop: s}, 'slow'); } return false; }); 
0
source

Presumably you can just add a simple if that will only execute scrollable code if keyCode matches up and down:

 $(document).keydown(function(e) { if (e.keyCode === 38 || e.keyCode === 40) { // Your code return false; } }); 

Here's a simple demonstration of this: http://jsfiddle.net/yijiang/SceDY/1/


When looking at the code, you should probably also use the var keyword to limit the scope of the variables prev , next and s . The current code behaves erratically if there is anything other than pushing up and down.

+3
source

All Articles