Search code examples
javascriptkeyboard

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 ?


Solution

  • 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)