Skip to content

wtf? keydown, keyup vs keypress

Stephen Wicklund edited this page Mar 26, 2017 · 8 revisions

keydown/keyup vs. keypress

keydown and keyup events

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.

keypress event

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.

Example: pressing the 'a' key

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