Last active
February 12, 2021 16:55
-
-
Save vincentriemer/7800189306194197ded28892db96aafa to your computer and use it in GitHub Desktop.
Listening/Reporting when keys are being held in vanilla JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function registerKeyHoldEvent(key, onChange) { | |
const handleKeyDown = (evt) => { | |
if (evt.key === key) { | |
onChange(true); | |
document.removeEventListener("keydown", handleKeyDown); | |
const handleKeyUp = (evt) => { | |
if (evt.key === key) { | |
onChange(false); | |
document.removeEventListener("keyup", handleKeyUp); | |
registerKeyHoldEvent(element, key); | |
} | |
} | |
document.addEventListener("keyup", handleKeyUp); | |
} | |
}; | |
document.addEventListener("keydown", handleKeyDown); | |
} | |
let isDKeyPressed = false; | |
registerKeyHoldEvent("d", (isPressed) => { | |
isDKeyPressed = isPressed; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment