Implementing keyboard shortcuts can greatly improve the user interface of your web application. Interface navigation is a good place to start, for example if you are viewing a slide show of photos you may expect to be able to navigate through the photos using the left and right arrow keys on you keyboard. For an application that has a popup dialog very common functionality is the ability to push the escape key to cancel the dialog and close it.
It is quite straight forward to implement keyboard shortcuts in your web application. I will use jQuery to bind a function to the document keypress event.
Bind the keypress event
| $(document).ready( |
| $(document).keydown( function( e ) { |
| if( e.which == 27) { |
| closeDialog(); |
| } |
| }) |
| ); |
Alternatively if you are not already using jQuery on your page you may prefer to directly assign the function to the document.onkeydown.
| document.onkeydown = function( e ) { |
| if( e.which == 27 ) { |
| closeDialog(); |
| } |
| }; |
The closeDialog function simply hides the dialog its the same code that would be executed if the use had pushed the cancel button of the dialog.
Detect the Ctrl, Alt, and Shift keys
You may want to distinguish between the key combinations such as ESC and SHIFT+ESC. To detect if the Ctrl, Alt or Shift keys are pressed you can use the properties event.ctrlKey, event.altKey or event.shiftKey.
| $(document).ready( |
| $(document).keydown( function( e ) { |
| if( e.which == 27 && e.shiftKey ) { |
| closeDialog(); |
| } |
| }) |
| ); |
In the example above you can see the function closeDialog will only be executed if shift and escape are pressed together.
Common key codes
There are many sites where you can lookup all the key codes on. I have listed some common ones below.
Key
|
Key Code |
| backspace |
8 |
| tab |
9 |
| enter |
13 |
| shift |
16 |
| ctrl |
17 |
| alt |
18 |
| caps lock |
20 |
| escape |
27 |
| page up |
33 |
| page down |
34 |
| end |
35 |
| home |
36 |
| left arrow |
37 |
| up arrow |
38 |
| right arrow |
39 |
| down arrow |
40 |
| insert |
45 |
| delete |
46 |
Keyboards shortcuts are a great simple way to improve the useability of your web application, its important to remember your users will not know they can use keyboard shortcuts unless you tell them.
Sunday July 26 2009 11:50 a.m.