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
keydownevent is fired whenever you press a key. Thekeypressevent is fired only when said key outputs a printable character.That being said, pressing a key between
aandz, for example "a" will generate:keydownwith keyCode 65 (A)keypresswith keyCode 97 (a)So they are not equal for the general case. Whereas pressing "SHIFT + a" will generate:
keydownwith keyCode 16 (Shift)keydownwith keyCode 65 (A)keypresswith 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
keydownwith keyCode 49 (1)keypresswith keyCode 49 (1)So they are equal without pressing the Shift key, whereas pressing "SHIFT+1" will generate:
keydownwith keyCode 16 (Shift)keydownwith keyCode 49 (1)keypresswith 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
keydownandkeypress. CAPS LOCK won't affect numerical keys, so they will still have equal keyCodes forkeydownandkeypress.Other event modifiers such as CTRL, ALT, and the combination of them with SHIFT, won't generate printable characters, so while a
keydownevent will be triggered, nokeypressevent 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.