1

I'm developing a game in HTML5, and in my game you use the spacebar to shoot. This worked fine until I realized that on smaller screens the spacebar would scroll to the bottom of the page, hiding part of the game. How can I stop the browser's hotkeys from making the page scroll down? Or how can I freeze the scrolling where the person has it when they click the canvas. Here is the game's link: http://73.9.75.150:8886/zn/index.html

Key handling code:

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

window.addEventListener("keyup", function(e){
    keys[e.keyCode] = false;
});
Jacob Pickens
  • 471
  • 1
  • 7
  • 15
  • 1
    Possible duplicate of [Pressing spacebar moves page down?](http://stackoverflow.com/questions/2343573/pressing-spacebar-moves-page-down) – JJJ Oct 09 '15 at 22:17
  • 1
    Please show the relevant key-handling code in your question. In a general sense, you probably need to stop the key event's default behaviour using `event.preventDefault()`. – nnnnnn Oct 09 '15 at 22:17
  • @nnnnnn I added the code – Jacob Pickens Oct 09 '15 at 22:19

2 Answers2

4

Your typical event listener call looks something like this:

window.addEventListener("keydown", function (e) {
    // shoot stuff
});

The e parameter in the above callback is an event object. It has a method call preventDefault() which will, as the name implies, stop the default behavior of the event from occurring.

This is how you can use it:

window.addEventListener("keydown", function (e) {
    if (e.keyCode === Keys.SPACEBAR) { // pseudo-code for key detection

        // shoot stuff
        e.preventDefault();

    }
});

This is a standard function and will work in most modern browsers. You may have to handle some older browsers a little differently, or use a library takes care of the cross-browser event issues for you.

Cypher
  • 2,608
  • 5
  • 27
  • 41
4

Possible solution:

document.addEventListener('keydown', function(e){
  if(e.keyCode === 32){
    e.preventDefault();
  }
});
  • A good way to improve your answer would be to explain why this would be a possible solution. Welcome to Stack Overflow, and thanks for contributing! – krillgar Oct 09 '15 at 22:24