Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I give an HTML canvas the keyboard focus using jquery?

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.

like image 745
Steve Hanov Avatar asked Dec 01 '09 23:12

Steve Hanov


1 Answers

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

like image 61
Xavi Avatar answered Sep 19 '22 20:09

Xavi