Javascript 'keydown' event listener is not working

user1668814 picture user1668814 · Sep 21, 2013 · Viewed 11.5k times · Source

The mousemove event works and calls onMouseMove each time I move on the canvas. Although, the keydown and keyup events never work. I click on the canvas and hit some keys, but no event is triggered. Does anyone know why the events are not working? Thank you for any advice! I'm following the html5 course on udacity if anyone is curious where the code came from.

InputEngineClass = Class.extend({

keyState: new Array(),

setup: function() {
    document.getElementById("gameCanvas").addEventListener('mousemove', gInputEngine.onMouseMove);
    document.getElementById("gameCanvas").addEventListener('keydown', gInputEngine.onKeyDown);
    document.getElementById("gameCanvas").addEventListener('keyup', gInputEngine.onKeyUp);
},

onMouseMove: function (event) {
    console.log("Called onMouseMove");
    var posx = event.clientX;
    var posy = event.clientY;
},

onKeyDown: function (event) {
    console.log("KEY DOWN!!!");
    keyState[event.keyID] = true;
    gInputEngine.update();
},

onKeyUp: function (event) {
    console.log("KEY UP!!!");
    keyState[event.keyID] = true;
},  

update: function() {
    KeyW = 87;

    if(gInputEngine.keyState[KeyW]) console.log("FORWARD!!!");   
}  
});

gInputEngine = new InputEngineClass();

Answer

jfriend00 picture jfriend00 · Sep 21, 2013

I'll turn my comment into an answer so you can wrap up this question.

For a DOM object to receive keyboard events, they must first be capable of getting the keyboard focus on a page. Only then will keyboard events be directed to that object. The simplest way to do that for a canvas object is to give it a tabIndex attribute.

canvas.setAttribute("tabindex", 0);

You can see someone else's summary of that problem here: http://www.dbp-consulting.com/tutorials/canvas/CanvasKeyEvents.html