An important distinction is that it is easier to know if cntrl
and z
are pressed at the same time, but not as straight forward to detect if z
and x
are pressed at the same time. What is the best way to go about detecting when multiple characters are pressed at the same time?
This example uses event listeners to keep track of an object which contains all keys currently being pressed.
We can use this object to check if certain keys are pressed. This means that we can detect as many simultaneous key presses as a user's keyboard will allow.
Importantly it will let you detect when multiple characters are pressed at the same time.
const keysPressed = {};
document.addEventListener('keydown', (event) => {
if (!event.repeat)
keysPressed[event.key] = true;
//You can also include event.repeat as a condition in your cases if you wish an event to only occur once each trigger.
//You can also include Object.keys(keysPressed).length === 2 (for example) if you only wish the case to be valid if just two keys are pressed.
//Finally, instead of event.key === 'x' you can write keysPressed['x']. This would replace both non-default cases in the example. The result is that the event will continue firing if another key is pressed.
switch (true) { //You use true here because we are using logic to determine each case
case event.key === 'x' && keysPressed['z']:
case event.key === 'z' && keysPressed['x']:
console.log('Z and X pressed!');
break;
default:
break;
}
});
document.addEventListener('keyup', (event) => {
if (!event.repeat)
delete keysPressed[event.key];
});