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
If you want an easier way to generate the string for the shortcut, take a look at Jonathan Tang's Keycode.js.

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
document.onhelp = function () { return false; };
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 am using Mozilla Firefox 3.0.5 . While i am pressing Ctrl+F4 , the alert is coming instead of pressing
Ctrl + S .
please give me a step to solve my problem. The code is
shortcut.add
('Ctrl+S', function()
{
alert('Hi');
return;
}
,
{
'type':'keypress',
'propagate':false,
'target':document
}
);
Thanks & Regards,
S.Parthibhan .
to solve the F4, F5, F6 problem try this:
var precedente = 0;
shortcut = {
...
var ele = opt.target;
if (typeof opt.target == 'string') ele = document.getElementById(opt.target);
var ths = this;
shortcut_combination = shortcut_combination.toLowerCase();
//the function to be called at keyup
var funcReset = function(e) { precedente = 0; }
//The function to be called at keypress
var func = function(e) {
e = e || window.event;
...
if (code == 188) character = ","; //If the user presses , when the type is onkeydown
if (code == 190) character = "."; //If the user presses , when the type is onkeydown
// The user press "s" key and not only the F4 key
if ((code == 115) && (precedente == 83)) {
code = 83;
}
else {
// The user press "t" key and not only the F5 key
if ((code == 116) && (precedente == 84)) {
code = 84;
}
else {
// The user press "u" key and not only the F6 key
if ((code == 117) && (precedente == 85)) {
precedente = code;
code = 85;
}
else {
precedente = code;
}
}
}
var keys = shortcut_combination.split("+");
//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
var kp = 0;
...
//Attach the function with the event
if (ele.addEventListener) ele.addEventListener(opt['type'], func, false);
else if (ele.attachEvent) ele.attachEvent('on' + opt['type'], func);
else ele['on' + opt['type']] = func;
//Attach the function with the event funcReset
if (ele.addEventListener) ele.addEventListener('keyup', funcReset, false);
else if (ele.attachEvent) ele.attachEvent('onkeyup', funcReset);
else ele['onkeyup'] = funcReset;
},
...
ciao
Andrea
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
0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9'
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
This fix is absolutely required if you set your key combo in ****uppercase**** "CTRL+S" or "ctrl+S" etc. will fail without this
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?
and even on the website I cant get any example to work
which uses Modifier+Letter
it works fine with Modifier+Number
like
Ctrl+2 works
but
Ctrl+S doesnt work
Ctrl+a or Ctrl+A doesnt work
the default example after executing the code which was "Ctrl+Shift+X" did not work
and nor did these things worked on my other computer which is running IE 6.0.2900
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.
//Find Which key is pressed
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
character=character.toLowerCase(); // Added this line
I have converted the key character to Lowercase... and I am trapping keys onkeydown. onkeypress donot work on IE6.
Above change worked fine on IE6, FF3 and Safari. This patch was unsuccesful on IE7. Still figuring out a way out. Tested with "SHIFT+CTRL+C".
I'm new to this javascript / html stuff so forgive me if I'm asking a stupid question. I have numerous buttons on my screen that perform different tasks. My users have requested that I attach Fkeys to each of these buttons. (They prefer to use an f key rather than a mouse click). I'm trying to set up F10 to execute a program IF the user entries on the screen are valid. I have a function called validateform that checks for valid entries. How would I incorporate your shortcut.add code to do this? Here is my current code but I can't get function validateform to work.
Here is a portion of my form:
<FORM name="formx" METHOD="POST" ACTION="/VFI/BIN/astart.EXE" onsubmit="return validateform(this);">
<INPUT class="mybutton" TYPE=submit title="F10" value="Update" onclick="formx.buttont.value='UPDATE';">
If the users use the mouse and click the button, the form is validated but my shortcut below
is not validating the form (Buttont must have a value of update).
shortcut.add("F10",function() {
validateform
formx.buttont.value='UPDATE';
formx.submit();
});
Thanks for the work that you have done. My other f keys using shortcut are working fine.
This can be solved by adding the beliow line:
character=character.toLowerCase();
after the line:
var character = String.fromCharCode(code);
Actually this script is very useful for me.
Thanks for such great script, very nice indeed.
I used it in a page I am developing (not online yet) and it worked fine, however, another short script in the page for tooltips (called qtip from http://qrayg.com) which was working fine up till then suddenly stopped. Can you please help me? I´m stumped, I tried to figure out what the incompatibility is between the two but couldn´t.
Thanks in advance,
Daniel
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
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
I used it in a page I am developing (not online yet) and it worked fine, however, another short script in the page for tooltips (called qtip from http://qrayg.com) which was working fine up till then suddenly stopped. Can you please help me? I´m stumped, I tried to figure out what the incompatibility is between the two but couldn´t.
function removeShortcut(combination) {
var binding = bindings[combination];
delete bindings[combination];
if( !binding ) return;
var type = binding.event;
var ele = binding.target;
var callback = binding.callback;
alert( ele.removeEventListener + " - " + ele.detachEvent );
if (ele.removeEventListener)
ele.removeEventListener(type, callback, false);
else if (ele.detachEvent)
ele.detachEvent('on'+type, callback);
else
ele['on'+type] = false;
}
// ....
//Remove the shortcut - just specify the shortcut and I will remove the binding
remove: function(combination) {
combination = combination.toLowerCase();
removeShortcut(combination);
},
//Remove all define shortcuts
clear: function() {
for (var combination in bindings) {
removeShortcut(combination);
}
}
Please reply as soon as possible.
Im not able to catch the shortcut events along with Alt and Cntrl modifiers along with Alphabets(a-z or A-Z)
In using the shortcut.js below the CODE section.
Please help me out..
Im using the below code.
shortcut.add("Ctrl+D",function() {
alert("Saved!");
});
shortcut.add("Alt+L",function()
{alert("Help Me!");});
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
function init() {
//Calls the Search screen.
shortcut.add("Ctrl+1", function(){
alert("You have pressed CTRL+1");
displayKey();
return;
},{
'type':'keydown',
'propagate':false,
'target':document
}
);
}
This does not work. Nothing happens when the key combination is pressed:
Nice work on the shortcuts script. I am having a little difficulty getting it to work with letter combinations such as Ctrl+s. I am using XP with IE 6 sp2. Here is the snippet of code that does work:
function init() {
//Calls the Search screen.
shortcut.add("Ctrl+s", function(){
alert("You have pressed CTRL+s");
displayKey();
return;
},{
'type':'keydown',
'propagate':false,
'target':document
}
);
}
Any help would be appreciated.
Thanks In Advance,
b
Excellent work that gives a browser application the potential of windows application ---
But i am not able to figure out where the script is creating the problem --- I m able to create numeric shortcuts like Ctrl+ etc but not able to create shortcuts with alphabetic keys --- even i tried combinations with arroww keys and they also worked but help me in creating alphabetic shortcuts -- i m using the IE 6 and also checked in google chrome--- waiting for the fast reply---
Jatin
jonathan.tang.name/code/js_keycode
It may be useful if you want to allow users to specify their own hotkeys with a keypress, and save those keys for later event binding.
Thanks
Great Job..
But guys is there any key to block property key of keyboard..i.e from where we normally work as right click of mouse.
<script type ="text/javascript" src ="shortcut.js"> </script>
<script type ="text/javascript" >
shortcut.add("alt+f3", function() {
alert("Called");
});
</script>
<asp:Button ID="Button1" runat="server" Text="Button" />
how to fire the button event "click" if i use the "shift+p" or "shift+N+P"
Thanks.
Everything works like a charm unless U use Opera...
1. when wanting to use shortcuts in iframe make it have src=empty.html and put a function bindthemall() {//make your shortcuts here} in the head.
2. for FF - call the function in the empty.html as onload or on DOM ready function
3. for opera - call the function from the parent like this: document.iftamename.contentWindow.bindthemall() whenever you change designmode. (Opera loses keybindings when setting designmode on)
and it works!
Please advise.
shortcut.add
('Ctrl+Q', function()
{
alert('Hi');
return;
}
,
{
'type':'keypress',
'propagate':false,
'target':document
}
);
shortcut.add("F5",function(){
alert('Operation not permited');
return false;
}, {'type':'keypress'});
When i press the F5 everything goes as planned, but the problem is that when i press the "t" key the script run as if i pressed the F5 :\
If i remove the type option it functions normaly.
Sory for my bad english and thanks for this script. :)
I am using keyboard shortcuts to control the entire web application that I am working on. More specifically, I am using the Enter key to start editing the entry that is selected. Hitting enter again saves the text typed in the text area. I am over ridding the enter property in the text area. So hitting enter doesn't put a carriage return in the text area.
All this is working fine. However, I have text box that is used to leave comments. I want the Enter key to work normally in there. Is there a way for me to tell the script that you don't do anything in this textbox?
THe other alternative that I can think of is to disable shortcuts onFocus of the comments box and then re-enable them onBlur. But I am not totally happy with this solution.
Someone, please give me a better way to solve my problem.
Thanks,
Arpan D.
target - DOM Node
The element that should be watched for the keyboard event. Default : document
If U provide a good target it should react only on target object.
So just wrap all the enter-saved object in a div or something and try setting shortcut on this.
PS. Help with getting shortcuts in opera designmode iframe would be a good thing to give in return :P
I have used this library in my web app. I am extensively using the ALT key shortcuts. On Google Chrome, the ALT ket shortcuts are not working. Bsically the ALT key isnt getting caught. Any way to get it to work? Is there an update to this library? I love this library.
Thanks in advance,
Arpan.
I am using keyboard shortcuts to control the entire web application that I am working on. More specifically, I am using the Enter key to start editing the entry that is selected. Hitting enter again saves the text typed in the text area. I am over ridding the enter property in the text area. So hitting enter doesn't put a carriage return in the text area.
All this is working fine. However, I have text box that is used to leave comments. I want the Enter key to work normally in there. Is there a way for me to tell the script that you don't do anything in this textbox?
THe other alternative that I can think of is to disable shortcuts onFocus of the comments box and then re-enable them onBlur. But I am not totally happy with this solution.
Someone, please give me a better way to solve my problem.
Thanks,
Arpan D.
Unless an actual mouse click is instigated for a given URL, we are warned with a message across the top of the page/
Is their any known function we could use to trigger a new window, using the shortcut function to activate it ?
Thanks,
Gautam
I have added the shortcut for Ctrl+S .But If i am pressing Ctrl+F4 , the 'Hi' alert is coming .
If i use 'keydown' in 'type', the save dialog box will come while pressing Ctrl+S .
Please advise.
shortcut.add
('Ctrl+S', function()
{
alert('Hi');
return;
}
,
{
'type':'keypress',
'propagate':false,
'target':document
}
);
Maybe that will help you do redirection on the client side.
now i can hook a function on shift-tab to traverse input fields backwards.
shortcut.add("Shift+Tab",function() {
alert("Hi there!");
});
i will use this for navigating across fields.
thanks for sharing.
var character = String.fromCharCode(code)
Change to this.
var character = String.fromCharCode(code).toLowerCase()
code.google.com/p/chromium/issues/detail?id=2215
This causes any keyboard shortcuts with the ALT key to fail in Chrome.
You can rectify this by commenting out the following lines:
if(e.metaKey) modifiers.meta.pressed = true;
and
} else if(k == 'meta') {
kp++;
modifiers.meta.wanted = true;
Now obviously, this breaks things for the Mac if you want to check for the meta key. If you need the META keyboard shortcut, you could change the following line:
if(e.metaKey) modifiers.meta.pressed = true;
To something like:
if(e.metaKey && navigator.userAgent.toLowerCase().indexOf("chrome") == -1) modifiers.meta.pressed = true;
This would ignore the META key event in Chrome. Hopefully Google will resolve this bug sometime soon.
can any one give me full code with shortcut.js, im new to JS and need to learn.
Is there any chances of openening a new window using shortcut.add(). if yes please let me know.
- it work with numbers only, for example:
Ctrl+2: works
Ctrl+T: does not work
- If I specify any values for the third argument (optional), the
shortcut will not work, e.g:
shortcut.add("Ctrl+2", function() {alert('test');} : Works
shortcut.add("Ctrl+2", function() {alert('test');},
{
'type':'keydown',
'propagate':false
} : does not work
Any idea?
I am using IE7.
** GOT IT WORKING **
First off the event needs to be "keydown" for my IE7 Master / Content page to catch the Ctrl key. Otherwise the functions in Shortcut.js won't even bother to fire.
--> shortcut.add("Ctrl+s", function() {imgSave_Click();}, {'type':'keydown','propagate':false,'target':document});
And yes for what ever reason I need the option parameters included in this line.
The next item was in ShortCut js at approx line #46 I need to make the character variable lower case:
--> var character = String.fromCharCode(code).toLowerCase();
Once those two changes were made, presto things started to work. Hope someone out there finds this useful, and saves them about 2-3 hours of work :-)
well... I think I didnot save my 2-3 hours and ended up finding the same solution... But, It still doesn't work on IE8 [Emulated as IE7] and IE7. I am trying.. SHIFT+CTRL+C.
Any idea on this... bro?
Idem, on your site when i test with letters, it does not work. But it works fine with numbers.
But it works fine with options.
Please let me know for new version.
BR
It lacks a toLowerCase l46
var character = String.fromCharCode(code).toLowerCase();
Hope it helps
Your code is very helpful for me. But i have a problem, (ie) i load a html page inside a iframe, when the cursor is in the iframe>text field, it did not capture any keyboard shortcuts. Is there any ways to do this? thanks in advance.
Regards,
Ananthavel.S
I have placed the JS code both in Parent window and All Child windows(ie pages loading in IFRAME) but nothing works. Also i tried to get from window.getElementById('IFRAMEID'). But it does not help. Kindly let me know for any solutions.
shortcut.add("Shift+F5",function() {
alert("HGello");
},{
'type':'keydown',
'disable_in_input':false,
'target':window.child/parent
});
Thank you so much for your work
Regards
Aditya
But I'm getting one javascript error in the following line
//Find Which key is pressed
if (e.keyCode) code = e.keyCode; (error in code = e.keyCode condition)
So I commented the condition and directly using e.keyCode as follows
var character = String.fromCharCode(e.keyCode).toLowerCase();
Now it's working fine...will it create any problem...reply me at the earliest.
Thanks,
Johnny
If you have any control name in jsp as code then the line
if (e.keyCode) code = e.keyCode; (error in code = e.keyCode condition)
will throw js error...
Try to avoid using var name as code in js also...
However, I wonder if there is a way to clean up all the syntax warnings reported by www.jslint.com based on your code. It will help clean up the warnings generated in the Microsoft VS2008 IDE, when using your Javascript code, I suppose.
Thank you,
Really very fantastic script.....
but i need to restrict for mouse pointer key which is located between Ctrl and Alt ... can u tell me suggestion ...
if(element.tagName == 'INPUT' || element.tagName == 'BUTTON' || element.tagName == 'TEXTAREA')
That way the script won't fire if focus is on a <button> as well.
But I'm getting one javascript error in the following line
//Find Which key is pressed
if (e.keyCode) code = e.keyCode; (error in code = e.keyCode condition)
So I commented the condition and directly using e.keyCode as follows
var character = String.fromCharCode(e.keyCode).toLowerCase();
Now it's working fine...will it create any problem...reply me at the earliest.
Thanks,
Savas
if(code == 109) character="-";
I am trying to add shortcut for Alt+Home- that should take me to the main page of my site,
But instead it takes me to the home page set on my browser.
Surprisingly, when i put an alert in my function, it starts working as expected.
Any help would be appreciated.
Regards
Code
shortcut.add("Alt+Home",function() {
document.forms[0].action="My URL";
document.forms[0].submit();
},{
'propagate':false
});
shortcut.add("c",function() {
alert("Hi there!");
}); Thankyou weriy code
Nice and very useful for everyone.
But little problem i have,
My page has IFRAME in which i am showing pdf...
In that case to use shortcut, i have to click somewhere on document, then only it works.
Any suggestions?
Paresh
My page has IFRAME in which i am showing pdf...
In that case to use shortcut, i have to click somewhere on document, then only it works...
On load i am initiating the function, when i click ALT key first time, i am getting " Code is undefined" could u help me out
If you could fix this it would be really helpful.
Thanks a lot for this script, it is really nice.
thank you very much but i have seen this subject somewhere before also it is not explained well like that.
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.