Search code examples
keypresskeycode

how to define event for keyPressed/keyCode...?


A freshman here that's stuck and confused on an assignment.. I'm surely doing it wrong because I get error on keyPressed as event is not define, with the code below. How do I define event in this instances?...

function keyPressed()
{ console.log("keyPressed");
//  When any key is pressed:
//  - Make RestrictedSafeComb2 equal to the value of 'keyCode'
 event.keyCode = 'enter'
 RestrictedSafeComb2 = event.keyCode;
}

Solution

  • First of all keypress event is deprecated. I am not sure what the nature of your assignment is, but you might go ahead with keydown instead.

    Also keydown is the event you want your code to watch for and use its properties. I presume KeyboardEvent.code is what you want.

    More details on MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

    document.addEventListener('keypress', keyPressed);
    function keyPressed(e) {
      console.log (e.code)
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Document</title>
    </head>
    <body>
        
    </body>
    </html>