4

I tried with this code to detect two keyboard arrows being simultaneously pressed:

document.addEventListener('keydown', event => {

    if (event.keyCode === 38) {
        console.log('up Arrow')
    }

    if (event.keyCode === 39) {
        console.log('right Arrow')
    }

})

But it doesn't work, however hard I try to press them at exactly the same time.

How can I cleanly fix this and detect when both keys are down ?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Adrin
  • 585
  • 3
  • 11

2 Answers2

6

There's only one keyCode per event. You have to track the keys going down, and up:

// if you keep both up and down keys down, you'll get a message
let downKeys = {}; // the set of keys currently down
document.addEventListener('keydown', event => {
    downKeys[event.keyCode] = true;
    if (downKeys[38] && downKeys[40]) {
       console.log("both down!");
    }
});
document.addEventListener('keyup', event => {
    downKeys[event.keyCode] = false;
});

(you have to go full page to test this snippet)

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

Here I use 2 flags to check if you are holding the keys.

If both flags are true then it means that you are holding both keys. So, you can perform anything inside the condition.

let holdKeyUp = false;
let holdKeyRight = false;

document.addEventListener('keydown', event => {

    if (event.keyCode === 38) {
        holdKeyUp = true;
    }

    if (event.keyCode === 39) {
        holdKeyRight = true;
    }
    
    if (holdKeyUp && holdKeyRight) {
        console.log("Both keys are pressed.");
    }

})

document.addEventListener('keyup', event => {

    if (event.keyCode === 38) {
        holdKeyUp = false;
    }

    if (event.keyCode === 39) {
        holdKeyRight = false;
    }

})
holydragon
  • 6,158
  • 6
  • 39
  • 62