0

I’m trying to implement a keyboard shortcut that triggers when the user presses: • Windows/Linux: Alt + Z • macOS: Option + Z

The problem is with using event.code === 'KeyZ'. It works fine on a QWERTY keyboard, but breaks on other keyboard layouts (e.g., AZERTY or Dvorak), where the 'Z' key might be in a different physical position.

I want the shortcut to work based on the character ('z' or 'Z'), not the physical key.

How can I reliably detect Alt/Option + Z across platforms and keyboard layouts using JavaScript?

What I’ve tried:

        filter((event: KeyboardEvent) => event.altKey && event.code === 'KeyZ'),

Any best practices for layout-independent shortcut handling?

1 Answer 1

0

You should check event.key instead of event.code.

Because CapsLock may be enabled, or Shift held down, you'll need to check for both 'Z' or 'z', or do something like this:

filter((event: KeyboardEvent) => event.altKey && event.key.toLowerCase() === 'z'),

As per docs here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

The KeyboardEvent.code property represents a physical key on the keyboard (as opposed to the character generated by pressing the key)

Also here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

The KeyboardEvent interface's key read-only property returns the value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.

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

1 Comment

Thanks for you response. actually event.key works different on mac, when using option + s it produces different key on this platform and on different layout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.