Gotchas with keyboard events
A few days ago I saw several bugs introduced by a well meaning dev who wanted to heed the UIEvent.which deprecation announcement and use the .key property instead. But even if .which is deprecated - that's actually untrue for every browser out there at the moment - the implementation of replacement properties is not fully supported.
First, there is the complication of the effect of the Shift key on the .key property. If you press Shift+3, then .which will be '3' and .key will be '#' and, for Shift-A, 'a' and 'A'. And that happens on a standard United States keyboard layout. For other layouts it's different. There is the concept of a Dead key, which you press on some keyboards to get a character with the press of another key, like adding an accent. In that case the .key property reads 'Dead'!
Second, the .key property is not always there. For example the Edge (and probably Chrome) code to autofill fields is simulating typing (with isTrusted true) without specifying a key. This may not even be a bug, considering that Autofill is not supposed to depend on a specific keyboard.
Then there is a .code property that is supposed to show the physical key that was pressed on the keyboard, but it's only fully implemented in Edge and Safari. And you don't get '1', but 'Digit1' and 'KeyA' instead of 'a' and even stuff like 'Comma'.
And there are other obsolete, deprecated or never fully implemented properties on events: charCode, keyCode, keyIdentifier and so on.
So be careful on how you handle key events. It's a mess.
Comments
Be the first to post a comment