Overriding Browser-Default Keys in HTML5 Games
After receiving several 0/5 ratings on my space game on Newgrounds, I’ve discovered that many players of my game are unable to play because of their browser-default keybinds. For example, pressing spacebar causes the screen to scroll down in many browsers. Thankfully, this can be fixed with a little bit of JavaScript. Below are some ‘insertable’ lines of code to disable common gameplay keys.
Disable Spacebar
window.onkeydown = function(e) { return !(e.keyCode == 32); };
Disable Arrow Keys and Spacebar
window.addEventListener("keydown", function(e) { // space and arrow keys if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) { e.preventDefault(); } }, false);
For a quick way to get key codes for other keyboard keys, you can check here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes