user3050499
user3050499

Reputation:

Controlling how much the document scroll on up/down arrow

Is there any way in javascript by which we can control how much the document will scroll to (in terms of pixel) on pressing the up/down arrow of keyboard?

Upvotes: 2

Views: 2037

Answers (1)

Joeytje50
Joeytje50

Reputation: 19112

Yes. Just add an event handler to the keypress event, and then check if the key pressed is the up or down key, and if the focused element is the body via document.activeElement. It'd use a function like this:

$(document).keydown(function(e) {
    var n = 100;  //Enter the amount of px you want to scroll here
    if (e.which == 38 && document.activeElement == document.body) {
        e.preventDefault();
        document.body.scrollTop -= n;
    }
    if (e.which == 40 && document.activeElement == document.body) {
        e.preventDefault();
        document.body.scrollTop += n;
    }
});

That changes the amount of pixels scrolled to the amount entered at line 2 of that script. In this case, it'd be 100px.

Upvotes: 2

Related Questions