0

I am trying to prevent scrolling when I use arrow keys in my HTML5 game. It is a maze game that you control with arrow keys or buttons on the screen, but whenever I press the 'up' or 'down' keys, it always scrolls.I am using:

document.addEventListener('keydown', function(e){
    if(e.keyCode === 40) {
        down();
    } else if(e.keyCode === 38) {
        up();
    } else if(e.keyCode === 37) {
        leftclick();
    } else if(e.keyCode === 39) {
        rightclick();
    }
})

Is this possible with javascript? I want it to be able to scroll with my mouse, but not when I use arrow keys on my keyboard. My game is at http://thomaswd.com/maze. Please help. Thanks!

Thomas Lai
  • 317
  • 1
  • 5
  • 15
  • 1
    possible duplicate of [Body stop scrolling after keydown, keypress with jQuery](http://stackoverflow.com/questions/14320634/body-stop-scrolling-after-keydown-keypress-with-jquery) – epascarello Feb 15 '13 at 18:43
  • http://stackoverflow.com/a/4770179/410273 – andrewk Feb 15 '13 at 18:43

3 Answers3

2

Use e.preventDefault() to prevent the normal key action from taking place.

document.addEventListener('keydown', function(e){
    if(e.keyCode === 40) {
        down();
        e.preventDefault();
    } else if(e.keyCode === 38) {
        up();
        e.preventDefault();
    } else if(e.keyCode === 37) {
        leftclick();
        e.preventDefault();
    } else if(e.keyCode === 39) {
        rightclick();
        e.preventDefault();
    }

})

jondavidjohn
  • 59,273
  • 21
  • 110
  • 154
1

Try this:

document.addEventListener('keydown', function(e) {
        if(e.keyCode > 36 && e.keyCode < 41) {
            e.preventDefault();
        }
        if (e.keyCode === 40) {
            down();
        } else if (e.keyCode === 38) {
            up();
        } else if (e.keyCode === 37) {
            leftclick();
        } else if (e.keyCode === 39) {
            rightclick();
        }
        return false;
    }, false);
}
Teemu
  • 21,017
  • 6
  • 49
  • 91
0

Try to add e.preventDefault(); at the end

Alex Ovechkin
  • 800
  • 5
  • 20