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.
Update
This is the second version of this script. The following modifications were made...
- The single function method was abandoned for an object with two functions
- Shortcut Remove function added
- New option to disable shortcuts in textarea, input fields.
- New option to manually specify keycode to watch for.
- Meta Key for Mac supported (Thanks, Dj Walker-Morgan)
The documentation for the last version is still available.
Thanks for all the comments and suggestions, guys.
Demo
Just press the shown combinations - if the script works, the status will changed to 'Called'. For example, press the key '1'...
- 1
- Function Called : Not Yet
- Ctrl+1
- Function Called : Not Yet
- Alt+1
- Function Called : Not Yet
- Shift+1
- Function Called : Not Yet
- Ctrl+Shift+1
- Function Called : Not Yet
- Ctrl+Alt+1
- Function Called : Not Yet
- Shift+Alt+1
- Function Called : Not Yet
- Ctrl+2 - Remove Shortcut
- Function Called : Not Yet
If you click the 'Remove Shortcut' Link before pressing the Ctrl+2 Combination, the function should NOT be called. - 3 - With disable_in_input = true
- The function should NOT be called when typing '3' in the input field
Function Called : Not Yet - 4
- Function Called : Not Yet
This uses the 'keycode' option. - Ctrl+A - With propagate = true
- Function Called : Not Yet
If Ctrl+A is pressed, it will call the function and then propagate the event to the browser - selecting the text.
Try it out...
Documentation
shortcut.add()
- 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'
- disable_in_input - Boolean
- If this is set to true, keyboard capture will be disabled in input and textarea fields. If these elements have focus, the keyboard shortcut will not work. This is very useful for single key shortcuts. Default: false
- target - DOM Node
- The element that should be watched for the keyboard event. Default : document
- propagate - Boolean
- Allow the event to propagate? Default : false
- keycode - Integer
- Watch for this keycode. For eg., the keycode '65' is 'a'.
{ 'type':'keydown', 'propagate':false, 'disable_in_input':true, 'target':document, 'keycode':65 }
Example Code
shortcut.add("Ctrl+B",function() {
alert("The bookmarks of your browser will show up after this alert...");
},{
'type':'keydown',
'propagate':true,
'target':document
});
shortcut.remove()
Just one argument - the shortcut combination that was attached to a function earlier. Make sure that this is exactly the same string that you used while adding the shortcut.
Example Code
shortcut.add("Ctrl+B",function() {
alert("Bold");
});
//Remove the shortcut
shortcut.remove("Ctrl+B");
Supported Keys
The shortcut keys should be specified in this format ...
Modifier[+Modifier..]+Key
Example...
Ctrl+A
The valid modifiers are
- Ctrl
- Alt
- Shift
- Meta
You can specify a sequence without a modifier as well - like this...
shortcut.add("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.
License
BSD License
Other Libraries
There is a jQuery plugin available for this library - jQuery Keyboard Hooker Plugin by Tzury Bar Yochay

Comments
I love your scripts. They are very easy to use, they work perfect and the update with the disabling in input/textarea is the last thing I missed.
Great work, keep it coming :-)
Michael
You code works just fine for me.
I was looking disabling in input/textarea feature. Its great that you added it.
Cheers :)
Great Script, thanks for sharing.
i want to ask you one qustion ?
when i try to add a shortcut(Ctrl+S) it's work but after calling my function the save dialog appear how i can remove this dialog?
this is my code
shortcut.add("Ctrl+S",function() {
alert("test");
return false;
},{
'type':'keydown',
'propagate':false,
'target':document
});
However, I can't seem to capture the following characters: , < . >
Just trying to get the ","/"<" key to work, I've tried all of the following combinations:
Ctrl+,
Ctrl+<
Ctrl+Shift+,
Ctrl+Shift+<
None of the events trigger in IE7. This may apply to other special characters as well.
shortcut.add('ctrl+enter',function(){alert("Hello World");})
-Seth
i'm make test page and not execute....script error
i want know this code problem...
anyone show me correct source code ^^
thank you
=======================error source=============================================
<html>
<HEAD><TITLE>Handling Keyboard Shortcuts in JavaScript</TITLE>
<script type=text/javascript src="shortcut.js">
</script>
<script type=text/javascript >
function init() {
alert("init");
shortcut("Shift+F1",function() {
alert("Help Me!");
});
shortcut("Ctrl+S",function() {
alert("Saved!");
});
shortcut("Right",function() {
alert("Right");
});
}
</script>
</head>
<body onload ="init()">
test
</body>
</html>
======================================================================
shortcut.add( instead of shortcut(
this code propagate and open de file open box. But if we add a alert box in 'func' then will not to propagate. What is wrong?
shortcut.add("Ctrl+O",function() {
func("obj","id") ;
},{
'type':'keydown',
'propagate':false,
'target':document
});
function func(obj,id) {
var a;
a=1;
// if add this don't propagate. OK.
//alert("Hello Mr. Binny");
//but if remove this alert will propagate. Not OK.
}
With IE7, I add 'e.keyCode = 0;' to stop the event print for CTRL + P:
...
e.cancelBubble = true;
e.returnValue = false;
e.keyCode = 0;
But this don't work for IE6.
Thanks for your suport.
It helps me a lot for my final project.
But i was thinking, if i want to disable the printscreen by using your script.
Is it achievable?
thanks indeed.. great script anyway..
I will let you know then the script is updated
I just started to work my way into your script - fantastic lib, simply working and what I was looking for: thnx.
I found a single issue: is it true that there is no way to capture the release of the keyup of a pressed standalone ctrl?
shortcut.add('c',function(){cPressed=true;},{'disable_in_input':true});
shortcut.add('c',function(){cPressed=false;},{'disable_in_input':true,'type':'keyup'});
works as expected
shortcut.add('Ctrl',function(){cPressed=true;},{'disable_in_input':true});
shortcut.add('Ctrl',function(){cPressed=false;},{'disable_in_input':true,'type':'keyup'});
sets cPressed to true but not back to false :(
Id love to hear from you and once again:
thnx for you great work
pekue
Thoughts on this? Is there a way around this?
Is there any way out?
I like it very much
I can't seem to get CAPS lock to work on the Mac (haven't tried a PC yet) in Safari/Firefox 2.0.0.6/Camino .5
Thanks for this script.
Jason
1) assignment to undeclared variable shortcut
2) anonymous function does not always return a value
Easy to correct:
1) var shortcut = { (add "var")
2) "return undefined" instead of plain "return" in function "func" ?
Someone may integrate this into a larger application, so better to prevent any additional warnings :)
I've bound F1 to an alert, and the dialog box pops up fine. Nothing else happens on Firefox (even although without the binding it would pop up the help) but on IE7 it also switches to the Help screens.
Apart from that the library is wonderful.
Thanks
Phil Nelson
I've tried
Shift+/
?
Shift+?
/
No luck :( also Shift+3 is a bit funny in safari, it seems to do the action of the last pressed shortcut.
Cheers for the great script
great work on this script. Easy to use, working on all browsers and efficient.
I took the liberty to add a feature that I use all the time: the ability to add an execution scope to the callback function. All my javascript code is structured in classes, and when I declare a shortcut inside a class, I want the callback function to have access to the "this" variable as well.
Below is my modification of the add function for this in case you are interested:
Line 309, replace:
callback(e);
with:
AND add this to the "add" function definition:
'add': function(shortcut_combination, callback, opt, obj, scope) { ...
You will then be able to do stuff like this:
Cheers for the good script.
Patrick
shortcut.add
("Ctrl+S", function()
{
alert("You have pressed CTRL+S");
return;
}
,
{
'type':'keydown',
'propagate':true,
'target':document
}
);
shortcut.add("Ctrl+S",
function(evt) { alert('it works'); },
{'type':'keypress','propagate':false,'target':document}
);
tested with Fireox 2.0.0.7
< script>
shortcut.add
("Ctrl+S", function()
{
alert("You have pressed CTRL+S");
return;
}
,
{
'type':'keydown',
'propagate':true,
'target':document
}
);
shortcut.add
("Ctrl+F4", function()
{
alert("You have pressed CTRL+F4");
return;
}
,
{
'type':'keydown',
'propagate':true,
'target':document,
'keycode':115
}
);
</ script>
I use the script in a web aplication, and i need a shorcut to submit a form, I use too the form plugin of jQuery.
I have a big problem, when I pulse F4 for submit the form, the form submit many times, one, two, three, or any. I dont understand why because I only submit one time.
I need your help, tks
Is there a way to handle mousewheel up and down? shift+mousewheelup is another shortcut for Back which I would like to block.
This script is working pretty well except for "Ctrl+B" which is still propagated and display my bookmarks in Firefox 2.
Any idea on how to go over this ?
也许你看不懂这汉字。
Thank you very much!
Thanks for function "remove()".
Excellent..Great work.
Thanks you very much for this library.
shortcut.add("Down",function() {
alert("Hi there!");
},
{
'propagate':false,
'disable_in_input':true,
}
);
Is that something you've run across, or have any ideas on? Thanks,
Pete
FF2 > can't use the numpad numbers,
Opera 9.2 > Alt + any number doesn't work,
IE7 > also can't use the numpad numbers.
Define in shortcut.js this:
'num0' :96,
'num1' :97,
'num2' :98,
'num3' :99,
'num4' :100,
'num5' :101,
'num6' :102,
'num7' :103,
'num8' :104,
'num9' :105,
then
shortcut.add("num0",function() {
alert("num0");
});
does anyone has solution then plz mail me.
Thanks
I ve question,
can we define all keys?I mean any keys of keyboard.
shortcut.remove("Ctrl+A");
is this all i need?
I'll just say WOW and THANKS man.
I would like to use this function to disable F3 function in IE so that my Flash Application can use that. But still it opens up the search function. How is it? I had given propagate : false also. Nothing happens. Am I doing something wrong...
shortcut.add("F3",function() {
alert("Hi there!");
},{
'propagate':false
}
);
Note: As far you scripts propagation issue are considered. In I.E make e.keycode = 0 for special shortcuts like Ctrl+F and F5. As firefox is considered, event.preventDefault() works only on keypress. Hence use keydown in I.E and keypress in FireFox.
It would be great that for a new version of the library this keys will be implemented
Thankz
This is just awesome.
//Find Which key is pressed
var code =0;
if (e.keyCode)
{
code = e.keyCode;
if(code>90)
code= code - 64;
}
else if (e.which) code = e.which;
for(var i=0; k=keys[i],i<keys.length; i++) {
//Modifiers
if (k == 'plus')
k = '+';
Try
shortcut.add("Alt+f",function(e) { alert('it works'); },{'propagate':false});
If that did not work, try with a different event
shortcut.add("Alt+f",function(e) { alert('it works'); },{'type':'keydown', 'propagate':false});
or
shortcut.add("Alt+f",function(e) { alert('it works'); },{'type':'keyup', 'propagate':false});
or
shortcut.add("Alt+f",function(e) { alert('it works'); },{'type':'keypress', 'propagate':false});
Hopefully, one of these will work - but there is no guarantee.
I have certain little problem with shorcut.js in the case of assign "t" key and not F5 key. In this case, when you press the F5 key shorcut.js trigger the event assigned to the "t" key.
The same issue with the "s" and F keys, and for the "u" and F6 keys. You can obtain information about this issue in this link of the jQuery hotkeys plugin page.
I dont now if is the better way, but, the above issue can fixed adding this lines of code before the line forty six of shortcut.js:
// The user press "s" key and not only the F4 key
if( (code == 115) && (character == 's') ) character = '';
// The user press "t" key and not only the F5 key
if( (code == 116) && (character == 't') ) character = '';
// The user press "u" key and not only the F6 key
if( (code == 117) && (character == 'u') ) character = '';
Hope be usefull for anyone. Thanks a lot for your shortcut.js library :)
Thumbs Up!
Its really interesting...
Varun.P
only one thing:
This code doesnt work on I.E. Only with keydow:
shortcut.add("Down",function() {
alert("Hi there!");
},
{'type':'keypress'}
);
Any sugestions ?
unixpapa.com/js/key.html
Thanks
Have some ideea??
Thanks for this great piece of work. Totally excellent. Too bad I cannot type exclamation marks in this editor ;-) Anyway, I too ran into differences between FF and IE. The difference with keypress and keydown is annoying when trying to develop web apps that will be used on FF and IE. In order to solve this issue, I added thses lines to your script
var keyEvent = 'keydown';
if (navigator.appVersion.indexOf("MSIE")==-1) {
keyEvent='keypress';
}
Then I modified the defaults as follows:
var default_options = {
'type':keyEvent,
'propagate':false,
'disable_in_input':false,
'target':document,
'keycode':false
}
This basically solves my issue, at least under Windows. I haven't tried this with Linux yet but will. Please consider adding these lines to your otherwise great script or tell me if there are any issues with this "solution".
thanks, Wouter
Wouter
i want to know that
if i press P
is there anyhow that ctrl+p is executed followed by Atl+r followed by Alt+l
This is done to set printer setting to Landscape.
Good work. Works good.
I added a help function.
something like this:
// get a html overview of all the current shortcuts
'getShortCutsInfo':function() {
var str = '<table style="margin: 10 10 10 10">';
for (prop in this.all_shortcuts)
{
str += '<tr><td align="center">' + prop + '</td><td> - ' + this.all_shortcuts[prop].description + '</td></tr>';
}
str += '</table>';
return str;
}
and don't forget to add
'description':'unknown'
around line 17
and
'description': opt['description']
around line 203
print this list in an alert or a modalwindow
Regards
great work by the way
Other than that, you're a bit screwed for a decent/easy way to capture it. Perhaps consider some other language if you require it; maybe even a little applet?
Crisp
www.crispycrisp.org
Here is the patch.
44d43
< var code;
145d143
< var k;
225a224
>
I have tried-event.returnValue=false,
return=false,event.keyCode=0,
event.Cancel=true,
event.cancelBubble=true.But it is not working.
thank you very much.
regards
On the other hand, works fine in Mozilla, but I need to work in IE, any idea about that?
I've tested with different version of rico and prototype, but not work. I need to solve my problem asap.
Regards.
On the other hand, works fine in Mozilla, but I need to work in IE, any idea about that?
I've tested with different version of rico and prototype, but not work. I need to solve my problem asap.
I used javascript(.js) file for adobe illustrator cs. Now i like to add shortct key for my .js file. Could you please advice me.
Thanks,
Sel.
Would you take the risk of making your site unusable so it can't be stolen by some hypothetical leecher who won't have the ability to do anything with it?
and i there a way to redirect to another page in a different frame with target.
thanks for your help
I'm trying to use the library to popup a window when the user presses a function key. The url of the popup window would change based on the textbox.
I'm using ASP.NET as development environment.
Is it possible to have like target a asp TextBox, i.e. target:TextBox2
Thanks, Blerim
-keypress- does not work for me. Happens the samething with keypress such as keydown. I suposse keypress is activated just when you hold pressed the keyboard button. Please explainme what is the correct way. Thanks again.
and i there a way to redirect to another page in a different frame with target.
and i there a way to redirect to another page in a different frame with target.
-keypress- does not work for me. Happens the samething with keypress such as keydown. I suposse keypress is activated just when you hold pressed the keyboard button. Please explainme what is the correct way. Thanks again.
Thanks a lot to provide such a great script. As my requirement is as follows:
when i open a modal dialog window through java script, i don't want to allow user to take print screen. how to disable print screen. also tell me is there any way by which I can enable java script at client machine if it is disable.
Rajeev
Very simple to use, and works well with FF and linux
Thanks
thank you very much
|| element.tagName == "SELECT"
to the code where it shows:
if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
This will prevent the shortcut from being called when the user is working with an active select-box.
Thanks.
Thanks in advance
www.google.com/search?hl=en&q=javascript+shortcuts
shortcut.add('esc',function() { window.location='http://www.google.co.uk'; });
I have to use escape, which is a shame since the window.location function works with other shortcuts (CTRL+SHIFT+X for example). Also if you put an alert tag infront of the window.location it also works. But the code above does not. Any suggestions on how to implement this would be greatly appreciated (again it works fine in everything except Firefox on the Mac).
I want to use this to simply update my form. The save button saves and closes, whereas update saves and stays on the form, with the updated info using php.
How to I code, if they update with the shortcut Ctrl+U then submit the update button.
I have tried "document.searchemployee.update.submit()" but no joy.
Any help appreciated.
thank you very much
thank you too.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="/appname/js/shortcut.js"></script>
<script type="text/javascript">
shortcut.add("X",function() {
alert("Hello!");
});
</script>
</head>
<body>
<div>HELLO</div>
</body>
</html>
The scripts execute as I can set alerts inside them to verify they are getting called however, the added short cut does not function. Thoughts?
Great Job, excellent script. But have a problem with the following code. I want to capture keyup event on ctrl key.This is not working in IE. Can anyone solve my problem.
Thanks in advance,
Abhishek Goud.
----------------------------------------------------------------------------
****************************************************************************
----------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" src="shortcut.js"></script>
</head>
<body>
<script language="javascript">
shortcut.add("Ctrl",function() {
alert("Ctrl keyup...");
},{
'type':'keyup',
'disable_in_input':true,
'propagate':false,
'target':document
});
</script>
</body>
</html>
----------------------------------------------------------------------------
****************************************************************************
----------------------------------------------------------------------------
Can anybody tell me how to suppress Alt+Enter key combination in IE7
Thanks.
Solution?
However, the jquery plugin version works just fine.
Can anyone else confirm that this script works in FF3?
I am currently using Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008051206 Firefox/3.0
I would prefer to not have to use jQuery.
What could be the problem ? Thanks
Me.Controls.Add(New LiteralControl("<script> shortcut.add(" & """" & "ALT+1" & """" & ",function() {alert(" & """" & "Hi!" & """" & ");}); </script>"))
In the text area above, execute:
shortcut.add("c",function() {
alert("Hi there!");
});
Then try hitting 'c'. Nothing happens for me except that the mouse pointer disappears until I move the mouse again. Accunote's keyboard shortcut javascript library works though.
var character = String.fromCharCode(code).toLowerCase()makes it workCheers,
Dave
I was having that same problem.
And thank you Binny [exclamation mark]
Great work
Does the stopPropogation work if type is "keyup" for the key "down" (arrow)?
I tried with this script, and it did scrolled down, when I pressed down arrow.
I guess, if I do not want the scrolling on keyup, I need to make some combination with keydown and keyup.
Or maybe there is some simpler way?
Thanks,
Indris
it makes my application dev easier
Thanks a lot
this is how i'm putting it in my site
<script type='text/javascript' src='shortcut.js'>
shortcut.add("Ctrl+Shift+A",function() {
alert("ADMIN PAGE!");
},{
'type':'keydown',
'propagate':true,
'target':document
});
</script>
change this: var character = String.fromCharCode(code)
into this: var character = String.fromCharCode(code).toLowerCase()
I am having a few problems though.
First, I'm trying to install a listener for the ENTER key on an input element. Thing is, I already have an onKeyUp defined for the element and an onSubmit for the form (activated by a hidden submit button). Now, when I define an ENTER listener with your shortcut script, the onSubmit of the form no longer works when I press ENTER.
Another problem is that of different keyboard layouts when the subject of shortcuts is viewed from an international perspective. For instance, I live in the German-speaking part of Switzerland, and some of the effects I've stumbled across using your script with various shortcuts are...uh, well, let me say, quite interesting.
Any ideas?
Of course, if you need any further information, just let me know... ;-)
I have problem.
Great Script, thanks for sharing.
i want to ask you one qustion ?
when i try to add a shortcut(Ctrl+S) it's work but after calling my function the save dialog appear how i can remove this dialog?
I have a big problem in Firefox
Ctrl+F4 is not stop with e.stopPropagation() and e.preventDefault().
How can I avoid this bubble?
when I use shortcuts with
Modifier+Letter
they dont work
Ctrl+S Ctrl+B Ctrl+s Ctrl+b etc wont work
even the default Ctrl+Shift+X did not work nor did the Ctrl+A worked
which was in your site demo. It did select everything but the function wasnt called.
Modifier+Number works though.
like Ctrl+2 works or Ctrl+Shift+2 works
I tried both on IE 7.0.6000 (Vista) and IE 6.0.2900 (XP)
I dont understand since i am testing it on 2 different computers so it shouldnt be the computers
and it shouldnt be the os
since one is running Vista and the other is running XP
<script language="javascript" type="text/javascript" src="{$smarty.const.JS_DIR}shortcut.js">
</script>
<script language="JavaScript">
function init() {
shortcut.add("Ctrl+R", function() {
alert("ctrl+R");
});
shortcut.add("F5", function() {
alert("F5");
});
}
</script>
<body onLoad="JavaScript:init();">
</body>
Remember that the F5 works, meaning that all the links are working just fine, it is just I cant get the Ctrl+R and Ctrl+B work. Any clue guys? Thanks alot. What a great work this is.
This can be solved by adding the beliow line:
character=character.toLowerCase();
after the line:
var character = String.fromCharCode(code);
I've refactored the JavaScript code to make it cleaner and easier to read & maintain:
Please check it out at:
github.com/tiendung/javascript-utils/tree/master/shortcut.js
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.