1

I have an application that relies on the deprecated keyCode property for keyboard shortcuts. I need to update my code to use a modern alternative that works consistently regardless of the user's keyboard configuration or language.

The MDN documentation suggest using either KeyboardEvent.code or KeyboardEvent.key. However, neither one of them fully substitutes keyCode in my use cases. Initially, I decided to use code as it seems more language-independent. However, I encountered issues, such as having to handle both the regular keys and the numpad keys separately (Enter, NumpadEnter, Numpad1...).

The current problem I'm facing is caused by mismatched keyboard layouts. For example, when using a QWERTY physical keyboard with an AZERTY OS layout and pressing Ctrl+A:

  • Pressing the "A" (physical "Q") key gives: code = "KeyQ", key = "a"

  • My code check fails, because it expects "KeyA"

I could check key instead, but this breaks with non-latin languages where the same physical key produces different characters (Cyrillic, Greek, etc.). I'd need extensive checks to ensure all characters that previously worked are handled now, too.

My question is whether there is a better and more modern approach to handle keyboard shortcuts reliably. What are you using in your application as a replacement of keyCode?

1
  • Is using a library an option? Commented Nov 6 at 10:53

1 Answer 1

0

The basic technical issues are presented in UI Events KeyboardEvent code Values W3C Recommendation, 22 April 2025. It's not light reading. Users may be on PCs with language packs loaded for their own language keyboard lettering as well as layouts for other languages, switchable using keyboard language selection in the taskbar system tray under Windows for example. Software translates the key codes to language letters, which AFAIK browsers don't pass on to event handlers, just the key code.

Browsers really only provide the key code to work with in event processing. You may be able to determine what letter it maps to if the user is typing into an <input>, <textarea> or content-editable element by capturing the event beforehand to know the key code associated with new input.

If you are not translating the web page(s) into non-English languages the best and least complicated solution may be to leave the instructions in English and let the user go about their normal practice in dealing with English based web content.

If pages are being translated to non-English languages more context about what the user is responding to needs to be taken into account - are you looking for choices or words, alphabets may have more or fewer letters, the first letter of the language may not be the equivalent of "A", the last letter equivalent to "Z" etc.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.