0

I am using this code to allow scroll using keyboard arrows, the issue is that its smooth going downwards but not upwards. I also want it to scroll to each section instead of holding down the arrow. is this possible?

$(document).keydown(function(e) {
  switch (e.which) {
    case 38: // up
      document.body.scrollTop -= 500;
      document.documentElement.scrollTop -= 500;
      break;

    case 40: // down
      document.body.scrollDown += 500;
      document.documentElement.scrollDown += 500;
      break;

    default:
      return; // exit this handler for other keys
  }
});

$(document).ready(function(){
  window.focus();
});
body{
  height: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
codtex
  • 6,128
  • 2
  • 17
  • 34
RickyBobby
  • 25
  • 1
  • 5

1 Answers1

0

To animate scrolling to specific element, you can do this:

$('html, body').animate({
    scrollTop: $("#section-1").offset().top
}, 1e3); // 1sec

To find currently visible section, you could iterate over them and check it like this:

var $current = null;

$('.section').each(function() {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(this).offset().top;
    var elemBottom = elemTop + $(this).height();

    if (!$current && elemBottom <= docViewBottom && elemTop >= docViewTop) {
        $current = $(this);
    }
});

Then based on pressed key, select next or previous element via $.next() or $.prev() and use it when scrolling:

$('html, body').animate({
    scrollTop: $current.next().offset().top
}, 1e3); // 1sec

Here is a working plunker (still some bugs there, just a prove of concept):

https://plnkr.co/edit/GMVKhskBn2mt3OXiCRo6?p=preview

Martin Adámek
  • 16,771
  • 5
  • 45
  • 64