views:

500

answers:

2

I am implementing a game using Javascript, jquery, and the Canvas tag. How can I prevent the browser from processing keyboard shortcuts when the canvas tag has the focus? I have tried event.stopPropagation() and it has no effect.

I can pick up keyboard events. However, when the user presses the spacebar, the web page scrolls down in Firefox. The same happens with the arrow keys.

+1  A: 

Try event.preventDefault();. Also there are keypress, keydown, and keyup events... you could try each of them to see which works.

Caleb
+5  A: 

The root problem is that by default the browser doesn't make the canvas "focusable". The best workaround I could come up with is to set the tabindex on the canvas:

$("#canvas")
    // Add tab index to ensure the canvas retains focus
    .attr("tabindex", "0")
    // Mouse down override to prevent default browser controls from appearing
    .mousedown(function(){ $(this).focus(); return false; }) 
    .keydown(function(){ /* ... game logic ... */ return false; });

If for whatever reason you can't set the tabindex, you can also make the canvas "focusable" by setting contentEditable to true:

// Add content editable to help ensure the canvas retains focus
$("#canvas").attr("contentEditable", "true")
$("#canvas")[0].contentEditable = true;

This is the solution I came up with originally, but in my opinion it's a bit hackier than the tabindex option.

Another thing to consider is that browsers tend to outline content editable elements with a border. This can be off-putting to some users. Luckily, you can get rid of it with this bit of css:

#canvas { outline: none; }

I've tested both solutions in Chrome 3/4/5 and FireFox 3.0/3.5/3.6 on Windows XP, Mac OSX and Linux. Here's a working example: http://www.the-xavi.com/static/so-canvas-keyboard.html

Xavi