3
\$\begingroup\$

I need to receive keyboard events in a canvas element. Click events are received but key presses aren't.

Here is my code which doesn't handle key events:

var canvasElm = $('canvas');
Event.observe('canvas', 'keypress', function(e) {
    console.log('Key event is received!!');
    console.log(e);
});

How can I make it handle those key events?

\$\endgroup\$
1
  • \$\begingroup\$ Dupe, or at least helpful? \$\endgroup\$
    – Anko
    Commented Feb 28, 2013 at 23:48

2 Answers 2

2
\$\begingroup\$

I suspect the canvas never has the keyboard focus. Keyboard events will be sent to the Window object.

Try adding the events to the Window object. (NB: It might be clearer what's happening if you don't use JQuery)

\$\endgroup\$
1
  • 3
    \$\begingroup\$ +1 For "don't use jQuery" ;) And for finding the solution, of course! \$\endgroup\$ Commented Mar 1, 2013 at 10:07
4
\$\begingroup\$

I'm really sorry. I found the solution after ask the question by trying. As MarkR said, we need give focus on our canvas. Here is the pure javascript (without JQuery);

canvasElm.setAttribute('tabindex','0');
canvasElm.focus();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .