addEventListener for keydown on Canvas

Cbas picture Cbas · Oct 14, 2012 · Viewed 101k times · Source

I am trying to make a canvas app that responds to keyboard and mouse input. I have this code:

canvas = document.getElementById('canvas');
canvas.addEventListener('mousedown', function(event) {
    alert('mousedown');
        }, false);
canvas.addEventListener('keydown', function(event) {
    alert('keydown');
        }, false);

The 'mousedown' alert comes up whenever I click the mouse, but the 'keydown' alert never comes up. The same code works fine on JS Bin: http://jsbin.com/uteha3/66/

Why isn't it working on my page? Does canvas not recognize keyboard input?

Answer

hobberwickey picture hobberwickey · Oct 15, 2012

Set the tabindex of the canvas element to 1 or something like this

<canvas tabindex='1'></canvas>

It's an old trick to make any element focusable