Vu Vo
Vu Vo

Reputation: 91

JavaScript multiple keydown

First, I would like to thank all for your help and replies.

I'm working on a project that required users to press a key and hold it, it will trigger an action.

When the user presses another key ( still holing the first key), it will trigger another action.

However, I'm stuck getting JavaScript to recognize two keys being pressed at the same time.

var down = false;
var keys;

document.addEventListener("keydown", function (e) {
    if (down) {return;}
    down = true;
    keys = (keys || []);
    keys[e.keyCode]=true;
    if (keys[87]){
        console.log("1");

    }
    else if (keys[83]){
        console.log("2");
    }
    else if (keys[83] && keys[87]){
        console.log("sucessfull");
    }
} , false);

document.addEventListener("keyup", function (e) {
    down = false;
    keys[e.keyCode]=false;
    stop();
}, false);
<button id="up" onmousedown="Drive(1)" onmouseup="Drive(2)">UP </button>

Upvotes: 1

Views: 6024

Answers (1)

dave
dave

Reputation: 1207

  1. Removed the 'down' variable checks
  2. Removed the mouse button element thing - didn't seem relevant to your problem?
  3. Removed the extra HTML body
  4. Got rid of the else branching as it would be satisfied (by 87 or 83) before ever getting to the && condition

        var keys;
    
        document.addEventListener("keydown", function (e) {
            keys = (keys || []);
            keys[e.keyCode]=true;
            if (keys[87]){
                console.log("1");
    
            }
    
            if (keys[83]){
                console.log("2");
            }
    
            if (keys[83] && keys[87]){
                console.log("sucessfull");
            }
        } , false);
    
        document.addEventListener("keyup", function (e) {
            keys[e.keyCode]=false;
            stop();
        }, false);
    

Upvotes: 3

Related Questions