How to Create Custom Keyboard Shortcuts using JavaScript

To add custom keyboard shortcuts, you will have to keep track of the clicked-on keyboard keys to track down when a desired combination is clicked.

// Keep track of clicked keys
var isKeyPressed = {
    'a': false, // ASCII code for 'a'
    'b': false, // ASCII code for 'b'
 // ... Other keys to check for custom key combinations
};

document.onkeydown = (keyDownEvent) => {

 //Prevent default key actions, if desired
 keyDownEvent.preventDefault();

// Track down key click
 isKeyPressed[keyDownEvent.key] = true;

// Check described custom shortcut
if (isKeyPressed["a"] && isKeyPressed["b"])  //for example we want to check if a and b are clicked at the same time
 //do something as custom shortcut (a & b) is clicked
};

document.onkeyup = (keyUpEvent) => {

 // Prevent default key actions, if desired
 keyUpEvent.preventDefault();

 // Track down key release
 isKeyPressed[keyDownEvent.key] = false;
};

Related