How to handle keyboard shortcuts in JavaScript

November 10, 2023

A simple keyboard Photo by Sergi Kabrera on Unsplash

Listening for keyboard shortcuts

Handling keyboard shortcuts is really easy thanks to newer APIs. A keyboard shortcut usually follows the following pattern:

Modifier Key 1 + Modifier Key 2 (optional) + Alphanumeric/Arrow keys

Let's take an example - suppose you want to detect whenever a user presses something like "Alt + Arrow Left/Right".

Code

document.addEventListener('keydown', function(event) {
    if (event.altKey) {
        if (event.code === 'ArrowRight') {
            alert('Alt + Arrow Left were pressed');
        }
        if (event.code === 'ArrowLeft') {
            alert('Alt + Arrow Right were pressed');
        }
    }
});

The great thing about keyboard events is, you have these 4 properties on keypress/keyup/keydown event:

"altKey": false|true,
"ctrlKey": false|true,
"metaKey": false|true,
"shiftKey": false|true,

Key Codes Demo:

Check here for the demo around keycodes.

Toggle Full Screen
Donate