Is Shift the only key that can change the value of keyCode?

732 views Asked by At

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.

1

There are 1 answers

0
ffflabs On BEST ANSWER

The assumption is wrong. You see, the keydown event is fired whenever you press a key. The keypress event is fired only when said key outputs a printable character.

That being said, pressing a key between a and z, for example "a" will generate:

  1. keydown with keyCode 65 (A)
  2. keypress with keyCode 97 (a)

So they are not equal for the general case. Whereas pressing "SHIFT + a" will generate:

  1. keydown with keyCode 16 (Shift)
  2. keydown with keyCode 65 (A)
  3. 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

  1. keydown with keyCode 49 (1)
  2. keypress with keyCode 49 (1)

So they are equal without pressing the Shift key, whereas pressing "SHIFT+1" will generate:

  1. keydown with keyCode 16 (Shift)
  2. keydown with keyCode 49 (1)
  3. 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 and keypress. CAPS LOCK won't affect numerical keys, so they will still have equal keyCodes for keydown and keypress.

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, no keypress 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.