How to make keyboard shortcut event?

How do you create keyboard shortcuts so that, e.g., when a user presses down CtrlShiftC, the program calls a function.

1 Like

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.

2 Likes

I found a way to do it, nevermind

3 Likes

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)

2 Likes

eruda? “Your function”? What does that mean?

1 Like

eruda.init() is just a function I’m calling, you can replace it with whatever your code needs to do.

3 Likes

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

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.