views:

34

answers:

1

I'm making a game that involves, like all games, key presses. Only left and right arrow and the Space Bar. They work, but the browser is pre-set to scroll left, right, or jump down on those keys. Is there any way to unbind those keys in the code? Thanks.

A: 

you should be able to prevent the default browser behavior by returning false after the key is pressed. However depending on how you are intercepting the key events it seems to work different on different browsers and even for different types of keys (alpha vs 'command' keys)

jquery preventDefault and stopPropagation might also work, the comments at the bottom of this documentation give alot of good hints http://api.jquery.com/event.preventDefault/

based on the info there I put this small bit of code together, seems to stop the space bar and down / up arrows from moving the scrollbar in both opera and firefox

try this code (jquery needed) in firefox with firebug console enabled

$(document).bind('keydown, keypress', function(event) {
  console.debug(event.keyCode + " - " + event.which);
  // event.preventDefault();
  return false;
});
house9
I found this works in every browser I've tried except IE:window.onkeydown = function(e){ if(e.keyCode == 32 || e.keyCode == 37 || e.keyCode == 39){ return false; }}Does anyone know a way to do this in IE? Even if it is only IE, I know a way around that problem. I just need a way to do the same thing in Internet Explorer.
Doug
this post breaks it downhttp://www.quirksmode.org/js/keys.htmlcheck out the 'Test' form at the bottom and view source to see how they deal with key events - seems to work IE8, Firefox, and Chrome
house9