Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting two keyboard keys being down at the same time

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 ?

like image 909
Adrin Avatar asked Mar 05 '23 20:03

Adrin


1 Answers

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)

like image 97
Denys Séguret Avatar answered Mar 16 '23 01:03

Denys Séguret