Ropstah
Ropstah

Reputation: 17804

Is it possible to prevent document scrolling when arrow keys are pressed?

Very straightforward:

Is it possible to prevent the browser from scrolling when a user pressed arrow keys?

Upvotes: 1

Views: 4981

Answers (7)

star
star

Reputation: 1

listen to the keydown event and prevent the default behavior.

In jquery

$(document).on('keydown.yournamespace', function(e) {e.preventDefault();});

Upvotes: 0

Ryan Florence
Ryan Florence

Reputation: 13483

It seems many are saying not to break what the browser does.

I would argue the same, unless you are replacing it with similar or better functionality.

I frequently kill the keyboard scroll in elements with an overflow because I've added a keyboard event to the element where using the keyboard "down" and "up" keys selects the items (think of a finder or windows explorer window).

The default scroll made the interaction all whacky. If the top item were selected, then you key 'down', it would select the next item but then scroll the element down and hide what was just selected.

So I break the default scroll, and then add my own to scroll to the selected item if it is below (or above) the current scrolling view. That way it behaves exactly as any OS out there when key-ing up and down through files.

Just saying, break it all you want, but make sure you know why you're breaking it and the user doesn't notice a thing.

Upvotes: 2

Ian G
Ian G

Reputation: 30234

Probably, but it's not usually a good idea to break a convention that everyone knows and understands :D

Upvotes: 0

Jonathan Fingland
Jonathan Fingland

Reputation: 57167

yes. use something like: document.getElementById('yourID').onkeypress = HandleKeyPress;

function HandleKeyPress(e) {
    var e = e || window.event;
    switch (e.keyCode) {

        case e.DOM_VK_LEFT:
        case e.DOM_VK_RIGHT:
        case e.DOM_VK_UP:
        case e.DOM_VK_DOWN:
            if (e.preventDefault)
                e.preventDefault();
            else e.returnValue = false;
    }
}

Though it may not be a good idea to do so. just be sure that you're not overlooking a better approach.

Upvotes: 10

Alex Rozanski
Alex Rozanski

Reputation: 38005

Very straightforward: Yes, but don't do it.

Changing fundamental operation of how a browser operates just confuses or angers users, and makes the whole experience less user-friendly. The user should have ultimate control of the way his or her browser functions, not you. This is similar to blocking menu items from being accessed, or removing context menus etc.

Upvotes: 7

thatismatt
thatismatt

Reputation: 9842

in jQuery you could do:

$().keydown(function(e) { return e.keyCode != 38 && e.keyCode != 40; });

Upvotes: 1

Antony Carthy
Antony Carthy

Reputation: 5597

In JQuery

$("*").keypress(function(e){e.preventDefault(); return false;});

Upvotes: -2

Related Questions