Add keyboard shortcuts to your web app

Keyboard shortcuts are common place in desktop apps, to such an extent that you would probably be surprised if holding ctrl+s didn't save a document, or if holding ctrl+n didn't do some kind of new action. But with website's its a lot less common. The bigger email providers all now provide the support, but for the sites produced smaller companies out there it's still not the norm. Actually adding the support for it though is actually quite straight forward.

In this example I'm going to use jQuery but it's just as easy in everyday JavaScript.

1var isCtrl = false;
2
3$(document).keyup(function (e) {
4 if(e.which == 17) isCtrl=false;
5}).keydown(function (e) {
6 if(e.which == 17) isCtrl=true;
7 if(e.which == 83 && isCtrl == true) {
8 alert("Hello World");
9 return false;
10 }
11});

What is happening here is relatively straight forward. When you hold a key down, JavaScript will pick up an event that says which key was pressed by it's number. However what it can't do is pick up a combination, so if you do a ctrl+s what you get is two events (one for the ctrl and one for the s). So on every keydown if it's a ctrl we set the variable isCtrl to true, then on the next keydown we know it's a combination. The keyup detects the end of the ctrl being held down and sets the variable back to false.

The return false, when we've detected a ctrl+s is also very important as what this will do is stop the browser from carrying out any shortcuts it may have had for that combination.

So there we have it, in around 10 lines of code you can add some functionality to your web app, that seems really advanced but is actually really really simple.