Search code examples
javascriptkeyboard-events2d-games

keydown event is not being detected


I am quite new to JavaScript and I am making a small game on it as a project. I am trying to detect 'keydown' event but it is not working for some reason. I have been on this for hours but I cant figure it out.

var c = document.getElementById("myCanvas");
                 
c.addEventListener('keydown', keyDown);

function keyDown(e){
   console.log(e.key);
}

I have already tried the 'keypress' event, but that didn't work either. I have tried 2 mouse events and they are working perfectly so the problem is just with the keyboard events.


Solution

  • To listen window events, try this:

    window.addEventListener('keydown', keyDown);
    
    function keyDown(e){
        console.log(e.key);
    }

    To listen document events, this:

    document.addEventListener('keydown', keyDown);
    
    function keyDown(e){
        console.log(e.key);
    }