|
about
AboutjQuery.hotkeys is a plugin that let you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination. It is based on a library shortcut.js written by Binny V A. The syntax is as follows: $(expression).bind(<types>,<options>, <handler>);
$(expression).unbind(<types>,<options>, <handler>);
$(document).bind('keydown', 'Ctrl+a', fn);
// e.g. replace '$' sign with '€'
$('input.foo').bind('keyup', '$', function(){
this.value = this.value.replace('$', '€');
});
$('div.foo').unbind('keydown', 'Ctrl+a', fn);TypesSupported types are 'keydown', 'keyup' and 'keypress' OptionsThe options are 'combi' i.e. the key combination, and 'disableInInput' which allow your code not to be executed when the cursor is located inside an input ( $(elem).is('input') || $(elem).is('textarea') ). As you can see, the key combination can be passed as string or as an object. You may pass an object in case you wish to override the default option for disableInInput which is set to false: $(document).bind('keydown', {combi:'a', disableInInput: true}, fn);I.e. when cursor is within an input field, 'a' will be inserted into the input field without interfering. If you want to use more than one modifiers (e.g. alt+ctrl+z) you should define them by an alphabetical order e.g. alt+ctrl+shift Modifiers are case insensitive, i.e. 'Ctrl+a' == 'ctrl+a'. HandlerIn previous versions there was an option propagate which is removed now and implemented at the user code level. When using jQuery, if an event handler returns false, jQuery will call stopPropagation() and preventDefault() Live DemojQuery CompatibilityTested with jQuery 1.2.6 to jQuery 1.3.1 Browser support
If you happened to have a browser installed on a platform which I marked as '?', I will appreciate if you kindly run the demo and send over the results. Features added in this version (0.7.x)
Overriding jQueryThe plugin wraps the following jQuery methods:
Even though the plugin overrides these methods, the original methods will always be called. The plugin will add functionality only for the keydown, keyup and keypress event types. Any other types are passed untouched to the original 'bind()' and 'unbind()' methods. Moreover, if you call bind() without passing the shortcut key combination e.g. $(document).bind('keydown', fn) only the original 'bind()' method will be executed. I also modified the $.fn.find method by adding a single line at the top of the function body. here is the code: Plugin's Version jQuery.fn.find = function( selector ) {
// the line I added
this.query=selector;
// call jQuery original find
return jQuery.fn.__find__.apply(this, arguments);
};You can read about this at jQuery's User Group Overrides Browser Native Shortcuts (f5, Ctrl-l, etc)Firefox is the most liberal one in the manner of letting you capture all short-cuts even those that are built-in in the browser such as Ctrl-t for new tab, or Ctrl-a for selecting all text. You can always bubble them up to the browser by returning true in your handler. Others, (IE) either let you handle built-in short-cuts, but will add their functionality after your code has executed. Or (Opera/Safari) will not pass those events to the DOM at all. So, if you bind Ctrl-Q or Alt-F4 and your Safari/Opera window is closed don't be surprised. The following example omit the quick-search feature in firefox when typing '/' jQuery(document).bind('keydown', '/', function (evt){
alert("Hello Slash");
evt.stopPropagation( );
evt.preventDefault( );
return false;
});Note that I am calling preventDefault() and stopPropagation() inside the handler For some reason just returning false does not work. Current Version is: beta 0.7 |
Sign in to add a comment
There's a way to manage Ctrl+click? Thank you
Great code! One question, what about combining accelerator keys? (Shift+Crtl+A, Alt+Shift+K, etc.)
Answering my own question, Ctrl+Shift+, etc. all seem to work for me now. They didn't when I first tried it ....
I'm having troubles in IE only (works in Safari, Firefox):
I test for $(this).attr("onclick"), and if so add function () {$(this).click();}
Works great in Firefox and follows the preexisting onclick javascript, but doesn't in IE. Anybody else seeing this?
can this plugin help with manage "Shift+click"?? it's need for multyple selection in list (select some item set, how it's works in windows).
Works great, except that, if i have the focus in a text box, i get an error saying Error: that.allelement? has no properties Source File: scripts/jquery.hotkeys.js Line: 78 Am i doing something wrong? Is it possible to get over this? Thanks
Works great. Can't use the backspace key without going back a page though (firefox/win). Works in the demo, just not on my screen.. I must be missing sthg.
Hi!
How can i make a toggle effect? For example. Shift+1 -> div->display: none; shift+1 again div->display: block;
Hi! For the number pad, I temporary fixed this problem adding the next code in the variable: 'this.special_keys' in the jquery.hotkeys.js
this.special_keys = {......., 96:'n0', 97:'n1', 98:'n2', 99:'n3', 100:'n4',101:'n5',102:'n6',103:'n7',104:'n8',105:'n9',........};
the keycodes 96 to 105 are the number pad keycodes. For use this solution,
jQuery.hotkeys.add('n0',function (){ /YOUR CODE/}); //For 0 in the number pad. jQuery.hotkeys.add('n1',function (){ /YOUR CODE/}); //For 1 in the number pad.
It works in my Iceweasel (Firefox). I hope it will help someone.
Hu! I've implemented Command key support for mac. I don't think that people would use combinations like "Command+a" but today the plugin is "stealing" the command key (if I bind "C", then Command+C stops working.
Hope it helps: Lines 65:74
var code = event.which, type = event.type, character = String.fromCharCode(code).toLowerCase(), special = that.special_keys[code], shift = event.shiftKey, ctrl = event.ctrlKey, alt= event.altKey, cmd= e.metaKey, propagate = true, // default behaivour mapPoint = null;Line 86:
if(!shift && !ctrl && !alt && !cmd) { // No ModifiersLine 95:
=)
@rafudu Thank you! That was driving me crazy.
It might be worth starting a comprehensive list of keys that can be safely captured on the various platforms -- or if anyone knows of such a thing that exists, link to it. I've wasted quite some time trying out keys in the various browsers, and it seems that most obvious key combos have at least one browser irrevocably binding them. In CodeMirror I'm capturing tab, ctrl-y, ctrl-z on all browsers except Safari, where I bind ctrl-backspace to undo, ctrl-and , and ctrl-enter.
Anyone tested this with jQuery 1.2.6?
seems to work fine in jquery 1.2.6 (we're using on a web site and with in Adobe AIR 1.1)
I want to bind different F1 functions to separate elements on the page. It only seems to want to bind to one.
$.hotkeys.add('f1',{target:$('#text1')[0]}, function(){alert('text1');}); $.hotkeys.add('f1',{target:$('#text2')[0]}, function(){alert('text2');});F1 only works in #text1, but shows text2 alert message. What's the point of the target if the hotkey can only be bound once? Am I missing something?
Just a comment to say thanks for putting this up! It really short-cut the work on a troublesome page I'm doing.
Is it possible to simply cycle different functions with a single same key?
Line 71: "alt = event.altKey," does not appear to work correctly in jQuery 1.2.6.
I'm using IE7/Windows and it always returns "undefined". However, in jQuery 1.2.2, it worked correctly.
OK, I found the solution to the "altKey" problem.
Change line 71 from: "alt = event.altKey," to:
alt = event.originalEvent.altKey,
Source: http://groups.google.com/group/jquery-en/browse_thread/thread/83e10b3bb1f1c32b/0f0cfd0be9409d12?show_docid=0f0cfd0be9409d12
var selectorId = ((this.prevObject && this.prevObject.query)
Using this code is not quite safe as this.prevObject (which should be this.end() ) returns the selector from only the last method of the chain. And many jQuery methods (not, filter, add,...) use the internal pushStack method that returns a new jQuery object and saves the former to this.prevObject. But in the next version of jQuery there will be 'Internal Selector State Tracking' which is I think is just what you want: http://docs.jquery.com/JQuery_1.3_Roadmap
I try this with the target is text input, but it doesn't work :
$.hotkeys.add('Ctrl+f', {target:$('#date')}, function (){ $("#panel_search").fadeIn("slow"); });or I miss something?
@xundertanktop, What version are you using? Try the latest (0.7.7) Note the with the new api it would be:
$('#date').bind('keydown', 'Ctrl+f', function(){$("#panel_search").fadeIn("slow"); });@Comment by thedandruff, Sep 01 (6 days ago):
planning to add this feature as it is a standard in jQuery which uses this.pushStack and let you bind many funciton to the same event at the same target.
expect it with in few days from now.
@Comment by thedandruff, Sep 01, 2008
It is possible now - check out version 0.7.8.
-Tzury
Will it ever be able to capture PrintScreen? ?!?
I've written a library that does basically the opposite of shortcut.js. Instead of taking a key description string and binding an event handler, it takes a keyboard event and outputs a string suitable for shortcut.js event binding:
http://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.
Opera 9.62 does not always set event.crtlKey. When in a form field event.ctrlKey is always false. The Ctrl key does generate proper event.keyCode properties of '17'. This applies to the other modifier keys, as well. Firefox and Epiphnany work just fine as is. But for true portability, the code really must keep track of the keyup and keydown events from the modifier keys.
Hi, nice plugin! One problem, the following is not working in IE6/7: $('input').bind('keydown', 'return', function() { alert('test'); });
Although if I do $(document).bind... it works. Tested on version 0.7.8.
"Or (Opera/Safari) will not pass those events to the DOM at all."
Is there any way to get around this? Like, say suppressing the 'save as' window in opera for a ctrl+s?
ctrl + click would be nice...
I want execute set of statement on two even for example click or shortcut keys how I can I achieve that ?
click or Ctrl+s { do this; }
Nice plug-in! My ergo buddies will love this :)
One question/help needed:
Code Sample
`$(document).ready(function(){
});`Issue
The "disableinInput" isn't actually disabling my hotkey (e.g.ctrl+e). Is there any issue with my implementation?
P.S. Browser is IE6/7
the example above has a typo: 'disableinInput' should be 'disableInInput'
I spent hours trying to get this to work. The documentation needs to be updated with the spelling fix "disableInInput" as commented by chunzi.
Otherwise, great work.
Works great! I am now using it in a pirate game I am working on http://constantsail.com .
Thanks! Rob
Has anyone used this plugin with ASP.NET 3.5? When it is included on a normal aspx page, eg one with <form runat="server">, pressing the "Enter" key in a text box is still generating a postback. It is definitely coded in correctly.
Thanks, Mike
There's a small typo in "Options", the "i" ("in") in "disableinInput" should be uppercased ;-)
I have a textarea for the chat, I've added a shortcut for enter to send a message. But the new line gets into the text field. how can I say not to write new line into textarea?
Great plug-in... but if i add the following keys to your demo they don't work...
... jQuery(document).bind('keydown', ';',function (evt){jQuery('#other1').addClass('dirty'); return false; }); jQuery(document).bind('keydown', ':',function (evt){jQuery('#other2').addClass('dirty'); return false; }); ...
... <div id="_other1" class="eventNotifier">;</div> <div id="_other2" class="eventNotifier">:</div> ...
Unless there is something I am doing wrong I think you need to add some more keys to your test case (i.e. ';', ':', etc).
Cheers Anthony
Hi!
Is it possible to bind several keys to one action at once? I mean something like
$(document).bind('keydown', '1,2,3', function(){ alert('It works!'); });
Nice plugin by the way!