Tag: Keyboard Shortcuts
Hot Keys Made Simple

Hot Keys Made Simple

Previously I have blogged about how you can create keyboard shortcuts using JavaScript. In other words being able to add functionality to your web app for someone to do a ctrl+s. My previous example wasn't particularly hard and only used 10 lines of code, but this week I stumbled across a jQuery plugin that makes it easier.

http://code.google.com/p/js-hotkeys/

With this plugin, in just 1 line of code you can bind a function to a keyboard shortcut. What's more you don't even need to look up the correct keycodes as it takes a simple text parameters.

1$(document).bind('keydown', 'ctrl+c', fn);

Combine this with a function that just triggers a button click and you have some very cool advanced looking functionality written in around 5 - 10 minuets.

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.