1

How can I bind the up arrow (or any other key) to do the same work as scroll up programatically w/ jQuery or Javascript?

I'm using this code to detect the up & down arrow click:

$(document).keydown(function(e) {
    switch(e.which) {
        case 38: // up
        console.log("up");

        break;

        case 40: // down
        console.log("down");
        break;

        default: return; // exit this handler for other keys
    }
    e.preventDefault(); // prevent the default action (scroll / move caret)
});

So when I click the down arrow in this case, it should call "mouse scroll down".

Reason for this: I can scroll through content in a popup modal on my website with swipe up and down on a mobile device, and with mouse scrolling. What if you have a laptop and no mouse? Arrow up/down doesn't work...

Teh Toro
  • 41
  • 1
  • 6
  • This is quite complicated. Scrolling is like resizing not one, but a few thousand pixel by pixel events... – Jonas Wilms Sep 01 '17 at 20:36
  • your code is working fine for up and down arrow ( i checked it and it logs correct in console). so what's your problem – Alive to die - Anant Sep 01 '17 at 20:37
  • Possible duplicate of [How to scroll to an element inside a div?](https://stackoverflow.com/questions/635706/how-to-scroll-to-an-element-inside-a-div) – sergdenisov Sep 01 '17 at 20:41
  • @AlivetoDie - I wanted to call "mouse scroll" instead of just console logging "down" when clicking the down arrow. – Teh Toro Sep 01 '17 at 20:41
  • I am probably missing something, but arrow up/down keys perform scrolling already in my browser... – trincot Sep 01 '17 at 21:02

1 Answers1

1

I believe the arrow keys should already work for scrolling (it works for me on Stack Overflow anyway!), but if it didn't, I believe the "scrollTo" method could work for you:

var startingY = 0;

$(document).keydown(function(e) {
    switch(e.which) {
        case 38:
        startingY -= 20;
        window.scrollTo(0, startingY);
        
        break;

        case 40: 
        startingY += 20;
        window.scrollTo(0, startingY);
        
        break;

        default: return;
    }
    e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:5000px"></div>
Arnoux
  • 226
  • 2
  • 9