How do you create keyboard shortcuts so that, e.g., when a user presses down CtrlShiftC, the program calls a function.
This was how I did it on one of my Repls, I think you could adapt this:
let cPressed = false;
let dPressed = false;
let tPressed = false; // Feel free to rename these, but note that you'll have to change them in-function too.
function keydownListener(event) {
//console.debug(event.key);
if (event.key === "c") {
cPressed = true;
} else if (event.key === "d" && cPressed) {
dPressed = true;
} else if (event.key === "t" && dPressed) {
eruda.init(); // Replace with your function
document.removeEventListener('keydown', keydownListener); // Unregister the listener so we don't re-run
} else {
cPressed = false;
dPressed = false;
tPressed = false;
}
}
document.addEventListener('keydown', keydownListener);
Downside(?) to this code:
You can push the Keys in order, not necessarily having to hold them down.
I found a way to do it, nevermind
Using that, hereâs a simplified version of my code:
function keyupListener(e) {
if (
//e.shiftKey &&
e.ctrlKey &&
e.altKey &&
e.key === "d"
) { // ^ Comment out or remove modifiers you don't need
eruda.init(); // Replace with your function
document.removeEventListener('keyup', keyupListener); // Unregister the listener so we don't re-run
}
}
document.addEventListener('keyup', keyupListener);
This allows you to use the key names instead of numbers. (Which seems easier to me)
eruda
? âYour functionâ? What does that mean?
eruda.init()
is just a function Iâm calling, you can replace it with whatever your code needs to do.
The way I did it in fourth grade was just to set a variable to true on âkeydownâ event, and false on âkeyupâ (having a check to make sure theyâre pressing that one key, like ctrl, alt, etc.), and then having a keypress event and checking if the variable is true. And then if it is, run your code
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.