Handling Keyboard Shortcuts in JavaScript
Despite the many JavaScript libraries that are available today, I cannot find one that makes it easy to add keyboard shortcuts(or accelerators) to your javascript app. This is because keyboard shortcuts where only used in JavaScript games - no serious web application used keyboard shortcuts to navigate around its interface. But google apps like Google Reader and Gmail changed that. So, I have created a function to make adding shortcuts to your application much easier.
Old Version
This is the documentation for the old version of this script - a newer version is available.
Demo
Press any of the following key combinations...
Shift+F1 - Shows alert("Help Me!");
Ctrl+S - Shows alert("Saved!");
Right Key - Shows alert("Right");
Try it out...
Documentation
- First Argument : The Shortcut Key Combination - String
- The shortcut key combination should be specified in this format ...
Modifier[+Modifier..]+Key
. More about this in the Supported Keys section. - Second Argument : Function to be called - Function
- Specify the function here. This function will be called if the shortcut key is pressed. The event variable will be passed to it.
- Third Argument[OPTIONAL] : Options - Associative Array
-
This argument must be an associative array with any of these three options...
- type - String
- The event type - can be 'keydown','keyup','keypress'. Default: 'keydown'
- target - DOM Node
- The element that should be watched for the keyboard event. Default : document
- propagate - Boolean
- Allow the event to propagate? Default : false
{ 'type':'keydown', 'propagate':false, 'target':document }
Example Code
shortcut("Ctrl+B",function() {
alert("The bookmarks of your browser will show up after this alert...");
},{
'type':'keydown',
'propagate':true,
'target':document
});
Supported Keys
The shortcut keys should be specified in this format ...
Modifier[+Modifier..]+Key
Example...
Ctrl+A
The valid modifiers are
- Ctrl
- Alt
- Shift
You can specify a sequence without a modifier as well - like this...
shortcut("X",function() {
alert("Hello!");
});
The valid Keys are...
- All alpha/numeric keys - abc...xyz,01..89
- Special Characters - Every special character on a standard keyboard can be accessed.
- Special Keys...
- Tab
- Space
- Return
- Enter
- Backspace
- Scroll_lock
- Caps_lock
- Num_lock
- Pause
- Insert
- Home
- Delete
- End
- Page_up
- Page_down
- Left
- Up
- Right
- Down
- F1
- F2
- F3
- F4
- F5
- F6
- F7
- F8
- F9
- F10
- F11
- F12
These keys are case insensitive - so don't worry about using the correct case.
This library is in beta - so expect some problems. Suggestions are welcome.
Code
Download the shortcuts.js file.
It has just one function - you can move it to some other JS file in your project.
License
BSD License
blog comments powered by Disqus