- 
                Notifications
    You must be signed in to change notification settings 
- Fork 56
wtf? keydown, keyup vs keypress
event.keyCode and event.which properties of keydown and keyup events correspond to keyboard codes. This is probably what you are expecting when listening for keyboard events.
event.keyCode and event.which properties of keypress events correspond to ASCII codes, as opposed to keyboard codes. This means non display characters will not be fired on keypress, lowercase characters come out wrong and it's just confusing. For this reason, you can not use the keycode library with keypress events.
document.addEventListener('keydown', function(e) {
  // e.keyCode is 65
  console.log("Key Down", keycode(e.keyCode)) // => 'a' keycode correctly identifies letter 
})
document.addEventListener('keypress', function(e) {
  // e.keyCode is 97 :/
  console.log("Key Press ", keycode(e.keyCode)) // => 'Numpad 1'?? But we pressed 'a'! 
  // keycode has no idea what it's doing, lol.
})However, if you do need to use "onkeypress", you can convert the keypress event's "keyCode" to the character itself using String.fromCharCode(97) -- "a". You can convert back to the "keyCode" using "a".charCodeAt(0) -- 97.
You can also find a list of these "keypress" key codes here (including "backspace", "enter", etc.): https://github.com/edsilv/key-codes/blob/master/src/KeyCodes.ts#L112