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.
Summary
Simply prevent the default browser action:
If you need to support Internet Explorer or other older browsers, use
e.keyCodeinstead ofe.code, but keep in mind thatkeyCodeis deprecated and you need to use actual codes instead of strings: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
keysand 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.addEventListenerwindow.removeEventListenerKeyboardEvent.codeinterface