Reputation: 445
I have made a game using HTML5 Canvas Element, Javascript for facebook. You can visit it here, http://apps.facebook.com/snaqe_game. The problem I am facing is that when I press down arrow key, used for moving the snake implemented using Javascript onkeydown event, the game works normally but the scrollbars go up and down. I tried making an textbox(#activ) and setting focus to it. It worked but when I tried to make it invisible, it failed.
document.onkeydown = function(event) {
document.getElementById('activ').focus()
if (!allowPressKeys) {
return null;
}
var keyCode;
if(event == null) {
keyCode = window.event.keyCode;
} else {
keyCode = event.keyCode;
}
switch(keyCode) {
case 37:
if (direction != "right") {
moveLeft();
}
break;
case 38:
if (direction != "down") {
moveUp();
}
break;
case 39:
if (direction != "left") {
moveRight();
}
break;
case 40:
if (direction != "up") {
moveDown();
}
break;
default:
break;
}
}
Upvotes: 1
Views: 283
Reputation: 129812
At the end of your document.onkeydown
function (after line 197 in snake.js
), add
if (event.preventDefault) { event.preventDefault(); }
if (event.stopPropagation) { event.stopPropagation(); }
return false;
This prevents the browser from responding to the event, beyond executing your function.
You may also need to replace return null;
on line 161 with these three lines.
Upvotes: 1