Found a way to listen for multiple keypresses at the same time

I created code to listen for multiple keypresses at the same time.

// In this example, I will listen for "Control" and "Enter" keys being pressed at the same time.

let keysPressed = [];

document.addEventListener("keydown", (key) => {
  keysPressed.push(key.key);
  keysPressed = [...new Set(keysPressed)];
  if(keysPressed.includes("Enter") && keysPressed.includes("Control") && keysPressed.length === 2) { // If keysPressed includes Enter and Control, and making sure it's nothing else by using length
    // the code
  }
})

document.addEventListener("keyup", (key) => {
  if(key.key === "Enter" || key.key === "Control") {
    keysPressed = [];
  }
})

Edit
Added keysPressed = [...new Set(keysPressed)]; to remove duplicates

3 Likes

This has been a widely known technique for a while now.

1 Like

Oh… I didn’t know that lol. Just surprised at myself for figuring this out in less than 5 minutes without stackoverflow

2 Likes

Not sure what happened with the second part of my post. I congratulated you in the event you didn’t look it up.

4 Likes

Generally, I do this:

const Input = {};

window.addEventListener("keydown", function(e) {
	Input[(e || window.event).key] = true;
});
window.addEventListener("keyup", function(e) {
	Input[(e || window.event).key] = false;
});

Then at any point you can check if any key or combination is pressed likeso:

if (Input.Control && Input.Enter) {
	// do something...
}

You can use this site (which I may or may not have made :wink:…) to check information on any key.

2 Likes

@OmegaOrbitals I’m in awe of you

Googling all the time is so bad for the brain… It limits the problem solving capacities

2 Likes

I know this way works for any combination of keys, but can’t you just do this for this particular example:

document.addEventListener("keydown", (key) => {
  if(key.key === "Enter" && key.ctrlKey) { 
    // the code
  }
})

EDIT: I feel like I’m missing something obvious

2 Likes

You could, although often you want to be able to access this information globally so you’d use a global variable somewhere and in the event listener alter this global variable to reflect user input.

1 Like