I'm making a game using canvas, and javascript.
When the page is longer than the screen (comments, etc.) pressing the down arrow scrolls the page down, and makes the game impossible to play.
What can I do to prevent the window from scrolling when the player just wants to move down?
I guess with Java games, and such, this is not a problem, as long as the user clicks on the game.
I tried the solution from: How to disable page scrolling in FF with arrow keys ,but I couldn't get it to work.
For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).
Why not simply do
window.event.preventDefault()
? MDN states:Further readings:
Summary
Simply prevent the default browser action:
Original answer
I used the following function in my own game:
The magic happens in
e.preventDefault();
. This will block the default action of the event, in this case moving the viewpoint of the browser.If you don't need the current button states you can simply drop
keys
and just discard the default action on the arrow keys:Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:
References
window.addEventListener
window.removeEventListener