Simple Javascript Shortcut Keys (Free Download)

So you want to add some shortcut keys to your web app using Javascript? But some of the “simple solutions” on the Internet don’t really work as intended? Well, here’s a quick sharing of my own simple version – Read on!

 

 

TABLE OF CONTENTS

 

JAVASCRIPT SHORTCUT KEYS

For you guys who just want to use this as a “plugin”, here’s a “quickstart guide” (download link is below).

 

BASIC SHORTCUT KEYS

shortcut.html
<!-- (A) LOAD JS -->
<script src="shortcut.js"></script>
 
<script>
// (B) REGISTER SHORTCUT KEYS & START
// shortcut-in-small-letters : function to call
// use https://keycode.info/ to help you get the key names
shortcut.add({
  "control-alt-f" : () => alert("FOO!"),
  "control-alt-b" : () => alert("BAR!")
});
shortcut.start();
</script>

Yep. It’s really that simple. For you guys who just want to use this as a “plugin” without reading the entire tutorial:

  • Load shortcut.js.
  • Use shortcut.add() to register the shortcut keys, and specify which functions to call.
  • Finally, call shortcut.start() to start listening to the shortcut keys.

If you minify and gzip the Javascript, it only weighs in at a few bytes.

 

 

MORE USAGE OPTIONS

shortcut.html
// (D) PAUSE SHORTCUT KEYS
// shortcut.pause();
 
// (E) REMOVE SHORTCUT KEYS
// shortcut.del("alt-f");
// shortcut.del(["alt-f", "alt-b"]);
  • If you want to pause the shortcut keys, call shortcut.pause(). For example, disabling the shortcut keys when a popup is open.
  • Take note, shortcut.pause() will not remove any of the shortcut keys registered with shortcut.add(). Running shortcut.start() again will resume the keys.
  • If you somehow want to remove the shortcut keys, use shortcut.del().

 

HOW THE SHORTCUT KEYS WORK

With that, let us now move into how the script actually works. This section is for you guys who want to learn more or “deep customize” it.

 

PART 1) BASIC SHORTCUT KEY MECHANICS

shortcut.js
var shortcut = {
  // (A) PROPERTIES
  pressed : [], // current key presses
  actions : {}, // shortcut keys & functions to call

  // (B) KEYPRESS TRACKER
  track : (key, down) => {
    // (B1) ON KEY DOWN
    if (down) { if (!shortcut.pressed.includes(key)) {
      shortcut.pressed.push(key);
      let sequence = shortcut.pressed.join("-");
      if (shortcut.actions[sequence]) {
        shortcut.reset();
        shortcut.actions[sequence]();
      }
    }}
 
    // (B2) ON KEY UP
    else {
      let idx = shortcut.pressed.indexOf(key);
      if (idx != -1) { shortcut.pressed.splice(idx, 1); }
    }
  },
  // ...
};
  1. The properties.
    • shortcut.actions Contains SHORTCUT-KEY : FUNCTION as described in “basic usage” above.
    • shortcut.pressed The whole idea is to use this array to track the key sequence.
  2. The essential mechanics.
    • onkeydown will record the keystrokes into shortcut.pressed. Example – When the user hits alt-t, shortcut.pressed = ["alt", "t"].
    • Then, we simply “combine and match” the keystroke against shortcut.actions. Example – If the user hits alt-f, it calls shortcut.actions["alt-f"]().

 

 

PART 2) START & STOP LISTENING

shortcut.js
// (C) START/PAUSE LISTENING TO KEY PRESSES
up : e => shortcut.track(e.key.toLowerCase(), false),
down : e => shortcut.track(e.key.toLowerCase(), true),
start : () => {
  window.addEventListener("keyup", shortcut.up);
  window.addEventListener("keydown", shortcut.down);
  window.addEventListener("blur", shortcut.reset);
},
pause : () => {
  window.removeEventListener("keyup", shortcut.up);
  window.removeEventListener("keydown", shortcut.down);
  window.removeEventListener("blur", shortcut.reset);
  shortcut.reset();
},
reset : () => shortcut.pressed = [],
  • shortcut.start() Will attach the keystroke listeners, and start tracking the shortcut keys.
  • shortcut.pause() Will remove the keystroke listeners, and stop tracking the shortcut keys.
  • Take note, it is important to clear the key sequence on window blur. Example – When the user hits control-p to print the page, we clear shortcut.pressed so it will not be “stuck” with ["control", "p"].

 

 

PART 3) ADD & REMOVE SHORTCUT KEYS

shortcut.js
// (D) ADD SHORTCUT KEY ACTION(S)
add : keys => {
  for (let  of Object.entries(keys)) {
    if (shortcut.actions == undefined) { shortcut.actions = fn; }
  }
},
 
// (E) REMOVE SHORTCUT KEY ACTION(S)
del : keys => {
  if (typeof keys == "string") { keys = [keys]; }
  for (let sc of keys) {
    if (shortcut.actions != undefined) { delete shortcut.actions; }
  }
}

Lastly, these are pretty much just “data yoga”… We are just adding and removing entries from shortcut.actions.

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

 

BROWSER DEFAULT SHORTCUT KEYS

Remember that the users are still using a web browser? Every web browser has its own set of shortcut keys, the common ones being:

  • Ctrl-S: Save-As
  • Ctrl-P: Print
  • Ctrl-T: Open New Tab
  • Ctrl-W: Close
  • Ctrl-C: Copy
  • Ctrl-X: Cut
  • Ctrl-V: Paste

Here’s the thing. We can also set, for example, Ctrl-S as a shortcut key in our web application. But it will clash with the browser’s “save as” shortcut. At the time of writing, there doesn’t seem to be a  reliable way to disable or override the browser’s default shortcut keys.

So just be very careful with this one, I will recommend using a sequence of 3-keys instead of 2. For example, Ctrl-Alt-S instead of just Ctrl-S.

 

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *