Simple Shortcut Keys With Pure Javascript (Free Source Code)

Welcome to a tutorial on how to add shortcut keys with Javascript. So you are developing your own web app and want to add some shortcut keys… Or maybe you just want to put in a “top-secret shortcut key” to do some Easter eggs on your website.

Yes, it is actually pretty easy to listen to key presses in Javascript, and we only have to detect the sequence of key presses to fire up whatever you want to do. We will walk through how to do those in this guide – Read on to find out how!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TABLE OF CONTENTS

Download & Demo How It Works Useful Bits & Links
The End

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

DEMO & BASIC USAGE

shortcut.html
<!-- (A) LOAD JS -->
<script src="shortcut.js"></script>
 
 <!-- (B) FOR THE DEMO -->
<div id="demoA">CONTROL SHIFT L IS PRESSED</div>
<div id="demoB">CONTROL SHIFT U IS PRESSED</div>
 
<script> 
// (C) JUST USE SHORTCUT.SET() ON PAGE LOAD
// Use https://keycode.info/ to help you get the key name
// event.key in all small letters
window.addEventListener("DOMContentLoaded", () => {
  shortcut.set({
    "control-shift-l" : () => { document.getElementById("demoA").style.background = "LightGreen"; },
    "control-shift-u" : () => { document.getElementById("demoB").style.background = "LightGreen"; }
  });
});
</script>
CONTROL SHIFT L IS PRESSED
CONTROL SHIFT U IS PRESSED

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

  • Include the shortcut.js file in your project.
  • Use the shortcut.set() on page load to attach the shortcut keys.
  • This function takes in an object with the format of SHORT-CUT-SEQUENCE: FUNCTION-TO-CALL.

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

 

 

HOW IT WORKS

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

 

A) ATTACH KEY LISTENERS

shortcut.js
// (A) SET SHORTCUT KEYS TO LISTEN TO
listen : null,
set : (listen) => {
  // (A1) KEY SEQUENCE + FUNCTION TO RUN
  shortcut.listen = listen;

  // (A2) KEY PRESS LISTENERS
  window.addEventListener("keydown", (evt) => {
    shortcut.track(evt.key.toLowerCase(), true);
  });
  window.addEventListener("keyup", (evt) => {
    shortcut.track(evt.key.toLowerCase(), false);
  });
},

set() is the very first function we call to attach the shortcut keys to functions. What this does is essentially attach keyup and keydown listeners. Nothing more.

 

 

B) KEYPRESS TRACKING

shortcut.js
// (B) KEY PRESS SEQUENCE TRACKER
sequence : [],
track : (key, direction) => {
  // (B1) PREVENT AUTO CLEANING
  if (shortcut.junk != null) { clearTimeout(shortcut.junk); }
    
  // (B2) KEY DOWN
  if (direction) { if (!shortcut.sequence.includes(key)) {
    shortcut.sequence.push(key);
  }} 

  // (B3) KEY UP
  else {
    let idx = shortcut.sequence.indexOf(key);
    if (idx != -1) { shortcut.sequence.splice(idx, 1); }
  }

  // (B4) HIT SHORTCUT?
  if (shortcut.sequence.length != 0) {
    let seq = shortcut.sequence.join("-");
    if (shortcut.listen[seq]) {
      shortcut.sequence = [];
      shortcut.listen[seq]();
    }

    // (B5) PREVENT "STUCK SEQUENCE" WHEN USER LEAVES PAGE
    // E.G. OPEN NEW TAB WHILE IN MIDDLE OF KEY PRESS SEQUENCE
    else { shortcut.junk = setTimeout(shortcut.clean, 600); }
  }
}

track() is the one that does the shortcut key magic, and it is fired whenever the user presses a key.

  • Whenever the user presses a keydown, it registers into the sequence array. For example, control-alt-z will be ["control", "alt", "z"].
  • On a keyup, the key will “deregister” from the sequence array. For example, if the user releases the alt key in the middle of the above control-alt-z (but holds down control-z) – ["control", "z"].
  • Lastly, it runs the specified function if the sequence matches. I.E. seq = sequence.join("-"); if (listen[seq]) { listen[seq](); }.

 

 

C) CLEANUP

shortcut.js
// (C) AUTO CLEANUP
junk : null,
clean : () => {
  shortcut.junk = null;
  shortcut.sequence = [];
}

This is kind of a “prevention measure”.

  • The user may open a new tab by pressing the control-t shortcut key.
  • In this case, a problem arises. Since the Javascript will not register keyup on control-t, it gets “stuck” in sequence.
  • This is why we need a timer to periodically clean out the sequence array when no keys are being pressed.

 

USEFUL 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. As 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 *