Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML page scrolls on keydown

I have a game in which the player can move using the arrow keys, I when I hit the up or down arrows the screen also moves. Is there a way to disable this?

I'm using the following: Local HTML page, Google Chrome, Windows

(FYI - the entire page isn't displayed at one time)

Here is my code:

function moveCharacter()
{
    // left arrow
    if (keys[37])
    {
        move("left");
    }
    // up arrow
    if (keys[38])
    {
        move("up");
    }
    // right arrow
    if (keys[39])
    {
        move("right");
    }
    // down arrow
    if (keys[40])
    {
        move("down");
    }
}

document.body.addEventListener("keydown", function(e)
{
    keys[e.keyCode] = true;
    moveCharacter();
});

document.body.addEventListener("keyup", function(e)
{
    keys[e.keyCode] = false;
});
like image 870
DUUUDE123 Avatar asked Jul 22 '26 20:07

DUUUDE123


1 Answers

The reason this happens is because after you observe the arrow key press, the default action continues to happen - scrolling the screen. The

event.preventDefault()

method stops the default action of an event from happening.


Now, you only want to prevent the default action of the arrow keys, not all keys, or else you will lose other key events or functions like typing in an input field, for example. The code below encapsulates this idea.

document.addEventListener("keydown", function (e) {
  // Only intercept the arrow keys, not all keys
  if([37,38,39,40].indexOf(e.keyCode) > -1){
    e.preventDefault();

    // Your code
    keys[e.keyCode] = true;
    moveCharacter();
  }
}, false);
like image 86
Drakes Avatar answered Jul 24 '26 08:07

Drakes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!