How to Add Keyboard Shortcut Events Easily in JavaScript
I was looking for an easy way to handle keyboard shortcuts in a web application I had been working on.
I wanted to register key presses like the following: ctrl+z
, ctrl+shift+z
, alt+x
, m
, etc.
While there are plenty of solid libraries out there for this (Mousetrap, HotKeys, etc.), I wanted to create my own shortcuts in vanilla JavaScript.
I decided to go with the keydown
and keyup
handlers in this scenario.
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("keyup", handleKeyUp);
I needed to handle ctrl
, shift
, and alt
keyboard shortcuts, so naturally, I needed some sort of “state” for these three keys. For that, I created isPressed
.
let isPressed = {
ctrl: false,
shift: false,
alt: false,
};
I could then update isPressed
on each keydown
and keyup
event.
Then, on each non-ctrl
, non-shift
, and non-alt
key, I print out the resulting key press combination.
const getCode = (e) => {
e = e || window.event;
return e.key;
};
const handleKeyDown = (e) => {
e.preventDefault();
const key = getCode(e);
switch (key) {
case "Control":
isPressed.ctrl = true;
break;
case "Shift":
isPressed.shift = true;
break;
case "Alt":
isPressed.alt = true;
break;
default:
const { ctrl, shift, alt } = isPressed;
let pressed = "";
if (ctrl) pressed += "ctrl+";
if (shift) pressed += "shift+";
if (alt) pressed += "alt+";
pressed += key;
console.log(pressed);
break;
}
};
const handleKeyUp = (e) => {
e.preventDefault();
const key = getCode(e);
switch (key) {
case "Control":
isPressed.ctrl = false;
break;
case "Shift":
isPressed.shift = false;
break;
case "Alt":
isPressed.alt = false;
break;
}
};