Set up two event listeners on the document
, one for keydown and another for keyup.
Keep in mind that the keydown
event will trigger repeatedly. So, when you switch the value of variable x
to 1
, make sure to remove the event listener to prevent multiple executions. You can add back the listener when x
is changed to 0
.
let x = 0
const toggle = ({ code, type }) => {
if (code === "KeyC") { // check for the "c" key
x ^= 1 // toggle `x`
console.log(type, "set x to", x)
return true // return a flag so we know when x is modified
}
}
const keydownHandler = e => {
if (toggle(e)) {
// remove the event listener to avoid repeats
document.removeEventListener("keydown", keydownHandler)
}
}
document.addEventListener("keydown", keydownHandler)
document.addEventListener("keyup", e => {
if (toggle(e)) {
document.addEventListener("keydown", keydownHandler)
}
})