I am writing some javascript to handle keyboard input. At one point in my code, I make the assumption that keyCode for keyPress event != keyCode for keyDown event
if and only if the shift key is being held down.
Is this a correct assumption? Or are there other keys where this condition holds? Specifically, I'm concerned about alternate keyboard layouts such as AZERTY and QWERTZ.
The assumption is wrong. You see, the
keydown
event is fired whenever you press a key. Thekeypress
event is fired only when said key outputs a printable character.That being said, pressing a key between
a
andz
, for example "a" will generate:keydown
with keyCode 65 (A)keypress
with keyCode 97 (a)So they are not equal for the general case. Whereas pressing "SHIFT + a" will generate:
keydown
with keyCode 16 (Shift)keydown
with keyCode 65 (A)keypress
with keyCode 65 (A)So they are equal when the shift key is being pressed down.
For the numeric keys the behavior is inversed. Pressing "1" will generate
keydown
with keyCode 49 (1)keypress
with keyCode 49 (1)So they are equal without pressing the Shift key, whereas pressing "SHIFT+1" will generate:
keydown
with keyCode 16 (Shift)keydown
with keyCode 49 (1)keypress
with keyCode 33 (!)So they are not equal when Shift key is pressed.
Having CAPS LOCK ON, will set the letters to uppercase by default, so keyCodes will be equal for
keydown
andkeypress
. CAPS LOCK won't affect numerical keys, so they will still have equal keyCodes forkeydown
andkeypress
.Other event modifiers such as CTRL, ALT, and the combination of them with SHIFT, won't generate printable characters, so while a
keydown
event will be triggered, nokeypress
event will fire.I made a small jsFiddle example to compare the events. I added a bit of extra logic to pair the events when keypress and keydown are fired at once.