Which KeyboardEvent key to use

zzzzBov

This could alternatively be titled ”W3C standards writers are human and sometimes make foolish mistakes“.

You might think that writing JavaScript for the browser to listen for keyboard events is something that we'd have solved after 20 years. Unfortunately, like many things in JavaScript land, it's a mess caused by naïve implementations of multiple inconsistent standards.

Recently I discovered that the UI Events Specification removed keyCode and which from the KeyboardEvent interface. They are to be replaced by key and code, which are to be used to access the value of the key being pressed. While this change makes a lot of sense for future implementations, there are a lot of fuzzy details that need to be worked out in implementations so that users of the API can expect consistent results.

What doesn't make sense is the deprecation and removal of which and keyCode before the implementation of key and code. Currently, if you want to have accurate cross-browser support for keyboard events, you must rely on keyCode and which to accurately detect key values despite being deprecated. Additionally this change will cause significant breakage if any browser were to actually stop supporting keyCode or which.

I understand that both keyCode and which had some issues that needed to be resolved, but to tell people they shouldn't use those working properties at all and instead rely on inconsistent properties that aren't yet fully supported is foolish.

So what should a developer do?

My advice at this point is to continue using keyCode and which. Particularly if you're using jQuery because jQuery will continue to support the documented event.which until the jQuery team decides to follow their standard deprecation plan. This should provide an adequate buffer from browser implementations. Hopefully.