3
votes

I'm trying to implement keyboard shortcuts on the browser. When the event listener is fired, I want to make sure that only a certain key combination is being pressed and nothing else.
For example, if I want to register the key "A" as a shortcut, the code might look like the following.

document.addEventListener("keydown", (event) => {
    if (event.key.toLowerCase() === "a" && numberOfKeysCurrentlyBeingPressed === 1) {
        // Do something
    }
});

This would be triggered for A and not for something like Ctrl + A or A + B.

I thought about counting and keeping track of the number of keys being pressed with keydown and keyup event listeners, but some keys on some systems will trigger only one event listener(keydown or keyup) and not the other. Also, there are some inconsistencies with this approach, not making it a viable solution.

I'm looking for a way to know exactly how many keys are being pressed when keydown event listener is fired so that I can compare the number with the number of keys involved in a keyboard shortcut combination.

1

1 Answers

0
votes

Using the keyup event and keydown you could keep track of how many keys are pressed like so:

var keyPresses = 0;

window.addEventListener('keyup', (e) => {
  keyPresses--
})

window.addEventListener('keydown', (e) => {
  if (!e.repeat) {
    keyPresses++
  }
  if (e.key.toLowerCase() === 'a' && keyPresses === 1) {
    //do something
  }
})