Teh Toro
Teh Toro

Reputation: 41

How to be bind up arrow to "scroll up" and down arrow to "scroll down" in jQuery or Javascript?

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...

Upvotes: 1

Views: 2061

Answers (1)

Arnoux
Arnoux

Reputation: 236

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>

Upvotes: 1

Related Questions