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.
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 ofp
is actually going to beP
(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: