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

Comments
Thanks!
Thanks so much for trying to help me. I think all we would need to capture is input type of text and textarea's. Right? I included my email address in this post.
Thanks again,
Phil
Phil
I used library like this....
<body onkeypress="return noNumbers()"> <script type="text/javascript"> function noNumbers() { shortcut("Alt+X",function() { alert("Hi there!"); }); } function shortcut(shortcut,callback,opt) {....} </script>PLz help me.I'm new to java script<body onkeypress="return noNumbers()">should be
<body onload="noNumbers()">A better way of doing that is to avoid using the 'onload' attribute in the body tag. Instead use this codewindow.onload=noNumbers;great script! I want to use it in my application. It works fantastic for "ctrl+n" but not for "ctrl+p". The print dialogue will be opened in IE.
How can I avoid that?
shortcut("control+P",function() {});
Thank you!
but does it support Macintosh? Linux?
just try it... :-)
at least it works with safari 2.0.3.
The right key - the callback function will have one argument - the event object. You can find the source of the event and see what kind of tag it is.
I assume the script can, but I guess the question is... will the author be doing this?
Firstly thatnks for your efforts and for releasing this neat little library, it will allow developers to add a little extra into their accessible websites. I was wondering though if you have any form of licensing for it o if it's just a freebie for the community? I plan to use this for my own web development but would also love to introduce it at work. Thanks.
I just wanted to thank you for this nice piece of code.
Keep up the good work!
Very interesting script , it is so easy for use and good tool for navigation in website
http://developer.mozilla.org/en/docs/DOM:event.stopPropagation
http://developer.mozilla.org/en/docs/DOM:event.preventDefault
* propagate:false is unreliable. For example, Ctrl+S still opens the save screen, and characters typed in the textbox still appear; but cursor keys don't propagate.
* <modifier>+<key> will be caught by <key>. If there are event handlers for both, the one for <key> will fire first.
* Ctrl+Alt+<direction> shortcuts don't work.
* Non-english keyboard layouts are a mess. It will not catch the same character; it might or might not catch the same key.
Unified key event handling in web browsers is a daunting task. It causes a lot of head aches, and while it is crucial for many modern web applications, almost nobody does really take care of that (particularly not the browsers themselves).
Anyway, there is good news for all developers, since the open source JavaScript framework qooxdoo.org has tried to resolve those nightmares as complete as possible. This technical article and the references therein explain all the fundamental problems behind such a unified key event handling and the cross-browser/cross-plattform solution provided by qooxdoo. Hope that helps. :-)
It is fine work.
I am tring to make a key board layout for my owen lanugage. So i like to replace my key press with a unicode. Suppose if i press 'j'i like to replace it with 'ক'. It is good when i press a key it dont place a key there. I just need to place a unicode where my cursor is blinking.
Please can any body help me.
Thank you.
OK, I need the solution to Tgr's problem (post: Tgr at 20 Apr, 2007 04:05). Have you got the time to fix it? And Paco, I tried replacing keydown by keypress, but it doesn't seem to work even on FF.
Thanks in advance,
Arpan D
ie. a page with input boxes (and textareas!) on it, if they are in focus, I don't want it to navigate to a different page when they press a key..
Thanks!
Rudi
I am making an ajax interface with fake back-button functionality..
If I add :
shortcut("Alt+Shift+d",function() {
alert("Hi here!");
});
and
shortcut("Shift+d",function() {
alert("Hi there!");
});
And press "Alt+shift+d" i get "Hi here" followed by "Hi there"...
Any way i can only have "Hi here" ?
what about this solution ..
after declaration of special_keys change the following code:
############################################################
#############################################################
continue original with callback(e);
// replace the "if(kp == keys.length) {" line with this:
var mod = 0;
if(e.ctrlKey) mod++;
if(e.shiftKey) mod++;
if(e.altKey) mod++;
if(kp == keys.length && (kp == mod+1)) {
Like Alt+Down to open a dropdownlist?
if (event.keycode==13)
{
event.altdown=True
event.keycode=40
}
doesn't seem to work...
Any Ideas??
thank you sensei^^
THANKS!!!
Just a quick info; In Safari, the shortcut keys which are already assigned to some functions, cannot be assigned in javascript. For instance; CTRL+V will not be picked up by the event listener and will therefore not be processed.
For me that is a big issue as I do not want people to paste rich text into the wysiwyg editor I'm building for one of my websites. As far as I know there is not a possibility to paste rich text as plain text using javascript in firefox/safari... too bad.
If you happen to know a solution to this problem (cancelling the CTRL+V in safari or making it possible to paste rich text as plain text using JS) please let me know.
Keep up the great work!
But propagate = false doesn't work for Firefox 1.5
Anyways, I need some help on the shortcuts lib for js.
I need to know how to "delete" or "disable" a shortcut I created earlier in the script
Many thanks, loinsees@gmail.com
In Firefox, Ctrl+W is "Close tab" or "Close browser window (If no tabs left)"
You can override this by doing: shortcut("Ctrl+W",function() {return false;});
Thanks,
for example
shortcut("Alt+string",function() {
alert("Hi here!");
or
shortcut("string",function() {
alert("Hi here!");
any ideas?
<html>
<head>
<script type="text/javascript" src="./shortcut.js"></script>
</head>
<div id="idDebug"></div>
<script>
var o_Debug=document.getElementById("idDebug");
o_Debug.style.position="absolute";
o_Debug.style.left=160+"px";
o_Debug.style.top=120+"px";
o_Debug.style.width=100+"px";
o_Debug.style.height=100+"px";
o_Debug.style.backgroundColor="#ff0000";
function test_keydown(event)
{
var e=window.event||event;
o_Debug.innerHTML="You have done!";
}
shortcut.add("a",test_keydown,{
'type':'keydown',
'propagate':false,
'target':o_Debug
});
</script>
</html>
Thanks for any help,
Kevin
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script src="shortcuts_v1.js" type="text/javascript" ></script>
<script type="text/javascript">
shortcut("Alt+A",function() {
alert("Hi there!");
},{
'type':'keydown',
'propagate':false,
'target':document
} );
</script>
</head>
test
</html>
thnks for your All help!!!
I cant seem to get anything to work...
please help.. thanks.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script src="shortcuts_v1.js" type="text/javascript" ></script>
<script type="text/javascript">
shortcut("Alt+A",function() {
alert("Hi there!");
},{
'type':'keydown',
'propagate':false,
'target':document
} );
</script>
</head>
test
</html>
thnks for your All help!!!
The above piece of code does magic!!!. I tried using it. Worked for me .
Thanks,
Kumara A.
on Firefox, "keydown" event doesn't override browser behaviour even with "propagate" to false. "keypress" does.
var shortCutKeyFor="Ctrl+Shift+M"// here any thing
shortcut.add(shortCutKeyFor,function(shortCutKeyFor) {
alert(shortCutKeyFor);
//here i want which short cut key is pressed as a string
});
i am using the shortcut.add as dynamically in far loop
here alert is showing [object] i want to know how to pass the shortCutKeyFor in to the function
shortcut("Ctrl+B",function() {
alert("The bookmarks of your browser will show up after this alert...");
},{
'type':'keydown',
'propagate':true,
'target':document
});
in above function
This works fine in FireFox but doesnt work in IE.Is there any modification needed to work with IE?
they seem to default to zoom in and out no matter what
I'm using it in http://code.google.com/p/zaapaas/source/browse/#svn/trunk/reform
mikeY
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.