AddDventListener not working

I took the basic Pong code on the Internet and tried to add keystrokes, the code is here: http://cssdeck.com/labs/ping-pong-game-tutorial-with-html5-canvas-and-sounds

I added the following:

canvas.addEventListener("keydown", handlekeydown, true);

After this existing code:

canvas.addEventListener("mousemove", trackPosition, true);
canvas.addEventListener("mousedown", btnClick, true);

And I also added:

function handlekeydown(e) {
  console.log("debug");
  console.log("keycode: "+e.keyCode);
}

But the function is never called, although I try to press various keys. Why is this? I'm sure Canvas is in focus.

+5
source share
3 answers

You cannot assign an event keydownto the canvas because you cannot focus the canvas with the cursor. You will need to assign an event to the window:

window.addEventListener("keydown", handle, true);
+15
source

You can try replacing the canvas with a window .

+5
source

, . :

//set attribute tabindex = 0 (other number), ensure the canvas in the focus sequence
//like this, you can focus canvas
//http://www.w3schools.com/tags/att_global_tabindex.asp
<canvas id="snake" width="400" height="600" tabindex=0 > </canvas> 

//then register keydown event
document.getElementById("snake").addEventListener("keydown", function(ev){
          console.log(ev);
}, true);
-2

All Articles