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
Try event.preventDefault();
. Also there are keypress
, keydown
, and keyup
events... you could try each of them to see which works.
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://xavi.co/static/so-canvas-keyboard.html