Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  70] [ 6]  / answers: 1 / hits: 137861  / 13 Years ago, wed, january 18, 2012, 12:00:00

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.


More From » canvas

 Answers
6

Summary


Simply prevent the default browser action:


window.addEventListener("keydown", function(e) {
if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);

If you need to support Internet Explorer or other older browsers, use e.keyCode instead of e.code, but keep in mind that keyCode is deprecated and you need to use actual codes instead of strings:


// Deprecated code!
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
e.preventDefault();
}
}, false);

Original answer


I used the following function in my own game:


var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.code] = true;
switch(e.code){
case "ArrowUp": case "ArrowDown": case "ArrowLeft": case "ArrowRight":
case "Space": e.preventDefault(); break;
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.code] = false;
},
false);

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:


var arrow_keys_handler = function(e) {
switch(e.code){
case "ArrowUp": case "ArrowDown": case "ArrowLeft": case "ArrowRight":
case "Space": e.preventDefault(); break;
default: break; // do not block other keys
}
};
window.addEventListener("keydown", arrow_keys_handler, false);

Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:


window.removeEventListener("keydown", arrow_keys_handler, false);

References



[#87933] Tuesday, January 17, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsleyashlynnh

Total Points: 64
Total Questions: 119
Total Answers: 98

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
kinsleyashlynnh questions
Tue, Sep 7, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Fri, Nov 8, 19, 00:00, 5 Years ago
;