Skip to content

Instantly share code, notes, and snippets.

@vincentriemer
Last active February 12, 2021 16:55
Show Gist options
  • Save vincentriemer/7800189306194197ded28892db96aafa to your computer and use it in GitHub Desktop.
Save vincentriemer/7800189306194197ded28892db96aafa to your computer and use it in GitHub Desktop.
Listening/Reporting when keys are being held in vanilla JS
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