For a keyboard shortcut, prefer event.key when the meaning matters and event.code when the physical key position matters. Do not start new code with keyCode; it is deprecated and fails badly across layouts and input methods.
window.addEventListener('keydown', (event) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
event.preventDefault();
openSearch();
}
});| Property | Example | Use it for |
|---|---|---|
key | "k", "Enter", "ArrowLeft" | The character or logical key |
code | "KeyK", "NumpadEnter" | A physical keyboard location |
repeat | true | Suppressing held-key repeats |
Keep shortcuts accessible
Do not hijack browser and assistive-technology shortcuts. Ignore shortcuts while a text input is receiving ordinary typing unless the shortcut includes an explicit modifier. For custom controls, use actual <button> elements where possible so Enter and Space behaviour comes for free.
keydownis for commands.beforeinputand input events are better tools for observing text entry, especially with IMEs and mobile keyboards.
Test a non-US layout and keyboard navigation before declaring a shortcut done. The reference is small; the edge cases are in the user's keyboard, browser, and assistive technology.
