Search code examples
javascripteventskeykeycode

how can I convert event.key into event.keyCode?


event.keyCode is now deprecated, so it's recommended to use event.key, but how can I get the "keyCode" from the "key"?

Now event.keyCode (but also event.which) are deprecated.

event.keyCode deprecation
event.which deprecation


Solution

  • 'a'.toUpperCase().charCodeAt(0)

    why toUpperCase()? because the keyCode is the ASCII code of the uppercase letter

    'a' keyCode is 65
    'A' keyCode is 65

    'A'.charCodeAt(0) is 65, but
    'a'.charCodeAt(0) is 97

    WARN: this works only for A-z and 0-9 characters, not for Arrow*, Escape, Enter etc. keys