how to check for two buttons on keyboard to be keyup at the same time in order to fire one function

426 Views Asked by At

I am trying to make a function that checks for two keys to be released up at the same time in order to fire one function. This is my code that I've been fiddling with for an incredible amount of time in attempt to accomplish this goal.

/* cn is used to stop the check after the two keys are 
pressed once at the same time. I am not really using this 
at the moment, but I will.
*/
var cn = true;
var pressed = {};

function try_buttons(event) {
  if(cn === true) {
    pressed[event.key] = true;
    if(pressed["Shift"] && event.key === "p") {
        console.log("worked");
    }
  }
}

Instead of doing it's intended purpose, it runs after shift is pressed at least one time and then any other time after that all it takes is pressing "p" to run the function.

1

There are 1 best solutions below

2
On BEST ANSWER

It looks like you store the key of each keyup event which is good. But I see three problems.

First, there will be instances where your condition is not true because when you press shift + p the key of p is actually going to be P (uppercase). So you'll need to .toLowercase() the keys.

The second problem is that you should be using pressed["p"] instead of reading the event directly.

The last problem is that after you store the state of a keyup event, you never reset the state. You need a timeout that clears the state to prevent the behaviour you're describing where you can get the console.log("worked") to run even though you're only hitting the "p" key.

This should handle what you're trying to achieve:

document.addEventListener('keyup', try_buttons)

let pressed = {}

function try_buttons(event) {
  pressed[event.key.toLowerCase()] = true

  setTimeout(function() {pressed[event.key.toLowerCase()] = false}, 200)

  if (pressed['shift'] && pressed['p']) {
    console.log("works")
  }
}