Question

Very straightforward:

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

in jQuery you could do:

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

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

listen to the keydown event and prevent the default behavior.

In jquery

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

In JQuery

$("*").keypress(function(e){e.preventDefault(); return false;});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top