My favorites | Sign in
Project Logo
             
Search
for
about  

About

jQuery.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);

Types

Supported types are 'keydown', 'keyup' and 'keypress'

Options

The 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'.

Handler

In 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 Demo

jQuery Compatibility

Tested with jQuery 1.2.6 to jQuery 1.3.1

Browser support

IE 6/7/8FF 1.5/2/3Opera-9Safari-3Chrome-0.2
Windows+++++
Mac OS Xx+?+x
GNU/Linuxx++xx

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 jQuery

The 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


Comment by gianiaz, Feb 04, 2008

There's a way to manage Ctrl+click? Thank you

Comment by kevinashworth, Feb 11, 2008

Great code! One question, what about combining accelerator keys? (Shift+Crtl+A, Alt+Shift+K, etc.)

Comment by kevinashworth, Feb 11, 2008

Answering my own question, Ctrl+Shift+, etc. all seem to work for me now. They didn't when I first tried it ....

Comment by kevinashworth, Feb 19, 2008

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?

Comment by jamiro.xmg, Mar 06, 2008

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).

thx.

Comment by swamyveera, Mar 14, 2008

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

Comment by pauldemott, Apr 13, 2008

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.

Comment by mibfire, May 14, 2008

Hi!

How can i make a toggle effect? For example. Shift+1 -> div->display: none; shift+1 again div->display: block;

Comment by willezumleben, May 25, 2008

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.

Comment by rafudu, Jun 25, 2008

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 Modifiers

Line 95:

         if(cmd) modif += 'command+';

=)

Comment by ken.pratt, Jul 25, 2008

@rafudu Thank you! That was driving me crazy.

Comment by marijnh, Jul 29, 2008

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.

Comment by az...@azeemazeez.com, Jul 31, 2008

Anyone tested this with jQuery 1.2.6?

Comment by funk.sf, Aug 11, 2008

seems to work fine in jquery 1.2.6 (we're using on a web site and with in Adobe AIR 1.1)

Comment by jjbut...@hotmail.com, Aug 29, 2008

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?

Comment by steven.hamblin, Sep 01, 2008

Just a comment to say thanks for putting this up! It really short-cut the work on a troublesome page I'm doing.

Comment by thedandruff, Sep 01, 2008

Is it possible to simply cycle different functions with a single same key?

Comment by dwtaylor99, Sep 02, 2008

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.

Comment by dwtaylor99, Sep 02, 2008

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

Comment by balazs.endresz, Sep 06, 2008

var selectorId = ((this.prevObject && this.prevObject.query)

(this0?.id && this0?.id) || this0?).toString();

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

Comment by xundertanktop, Sep 07, 2008

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?

Comment by Afro.Systems, Sep 08, 2008

@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 Afro.Systems, Sep 08, 2008

@Comment by thedandruff, Sep 01 (6 days ago):

Is it possible to simply cycle different functions with a single same key?I am

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 Afro.Systems, Sep 14, 2008

@Comment by thedandruff, Sep 01, 2008

Is it possible to simply cycle different functions with a single same key?

It is possible now - check out version 0.7.8.

-Tzury

Comment by eber.freitas, Oct 11, 2008

Will it ever be able to capture PrintScreen? ?!?

Comment by jonathan.d.tang, Oct 16, 2008

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.

Comment by sbergman27, Nov 07, 2008

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.

Comment by emma.sender, Nov 12, 2008

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.

Comment by ogle.ben, Nov 12, 2008

"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?

Comment by matrym, Nov 19, 2008

ctrl + click would be nice...

Comment by abhijeet1974, Dec 10, 2008

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; }

Comment by chunzi, Dec 25, 2008

the example above has a typo: 'disableinInput' should be 'disableInInput'

Comment by nmulvaney, Jan 01, 2009

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.

Comment by robkohr, Jan 08, 2009

Works great! I am now using it in a pirate game I am working on http://constantsail.com .

Thanks! Rob

Comment by GeyikliBaba, Jan 21, 2009

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

Comment by albrecht.andi, Feb 19, 2009

There's a small typo in "Options", the "i" ("in") in "disableinInput" should be uppercased ;-)

Comment by Arvids.Godjuks, Mar 16, 2009

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?

Comment by vdh.ant, Apr 19, 2009

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

Comment by pere.pasqual, Jun 18, 2009

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!

Comment by shallway.xu, Jul 16, 2009

Is $(document).bind( "keydown", "a+a", fn ); supported? //press 'a' twice

Great job though!

Comment by dennispopel, Jul 18, 2009

Great job.

Comment by alexlingris, Jul 23, 2009

Great job, I have a problem though.. The disableInInput works in half. I doesnt fire the function, but it doesnt print the letter in input either...

Comment by fahiemq, Aug 19, 2009

This is realy great for webapplications! is there a way to get it to work with the jquery toggle function.

for example if i hit the f2 button a div wil appear and if i hit it again the div will disappear?

Comment by devil.tsc, Sep 06, 2009

Great plugin, but i have one question. Is there any way of assigning my function to "ctrl+f" in Safari?

plain

$(document).bind(key_event, 'ctrl+f', function (evt) {

if($.browser.msie) {
event.keyCode = 0; event.returnValue = false;
event.cancelBubble = true;
}
else {
evt.stopPropagation(); evt.preventDefault();
} myfunction();
} works everywhere, but not in Safari 4.0.3 any thoughts?

Comment by devil.tsc, Sep 09, 2009

Guys, i really need help with Safari. Also preventDefault doesn't stop the default Safari's ctrl+p function.

Comment by devil.tsc, Sep 09, 2009

Also, is there any way of assigning ctrl +/ ctrl - keys to user functions and preventing the default zooming?

Comment by VersionFourX, Sep 10, 2009

Is there a way to enter the Konami Code with this plugin? Example (in order): up, up, down, down, left, right, left, right, b, a

Comment by ameen.mca, Sep 13, 2009

Hi All. Can I associate 3 key combinations (Ctrl+q+c)? I'm creating hotkey for menu and say the above combination is for Quote -> Create. I tried a lot but it doesn't works. Please suggest. It would be a great help.

Comment by Mustafayev.M, Sep 13, 2009

right button click mouse?

Comment by devil.tsc, Sep 14, 2009

So, everybody knows nothing about Safari? great. what about ctrl+/- is it possible at all? also Opera's alt + arrows =)

Comment by nicolas.loeuillet, Sep 17, 2009

Hi,

here is my code :

for (i = 1; i <= 9; i++) {
	$(document).bind('keydown', 
		{combi : i+'',
		disableInInput : true
		}, function(evt) {
		// my function 
		return false;
	});
}

I want disable the hotkeys on my input with disableHotkeys css class.

I try this code :

$('input.disableHotkeys').unbind('keydown', 
	{combi : ''+i,
	disableInInput : false
	}, function(){});

but it does'nt work.

Could you help me please?

Thx,

Nicolas

Comment by linjuming, Nov 07 (3 days ago)

can not unbind "Ctrl+(any)" "Shift+(any)" ,but can unbind "a","b" or any single key. why?

Comment by linjuming, Nov 07 (3 days ago)

my testing code, can not unbind the function:

function han(){
alert(1);
} function bindhotkeys(){
$(document).bind("keydown", "Shift+a",function(){han(); return false;});
} function unbindhotkeys(){
$(document).unbind("keydown", "Shift+a",function(){han(); return false;});
}

Comment by linjuming, Nov 07 (3 days ago)

but this can work

	function han(){
		alert(1);
	}
	function bindhotkeys(){
		$(document).bind("keydown", "a",function(){han(); return false;});
	}
	function unbindhotkeys(){
		$(document).unbind("keydown", "a",function(){han(); return false;});
	}

Sign in to add a comment
Hosted by Google Code