Add Handlers For Any Key Combination With jQuery

Posted By : todd sharp Posted At : August 4, 2009 9:00 AM Posted In: jQuery

5

js-hotkeys is an awesome jQuery plugin that lets you bind a function to just about any key combination you can think of. It can really come in handy to create custom keyboard shortcuts for your application.

Just drop the plugin into your app and you can simply call it like such:

$(document).bind('keydown', 'ctrl+c', fn);

And unbinding is as simple as, yep, just calling unbind:

$(document).unbind('keydown', 'ctrl+c', fn);

The plugin worked in every browser that I tested it in (FireFox 3.5, Safari, IE7, Chrome). You can bind to special keys (Esc, F1, F2) as well as modifiers (Alt, Shift, Ctrl) to create any shortcut you may need.

Check out the live demo to try it out.

In the next few days I'll blog about how I combined js-hotkeys with the fieldSelection plugin to enhance the blog entry editor in BlogCFC to allow for simple keyboard shortcuts.

Comments (5)

Jason Dean's Gravatar Wow, that is really cool! Thanks for the tip. I was just talking about keyboard shortcuts in AIR apps with someone yesterday. This will make it much easier.

todd sharp's Gravatar Yeah, it is a very cool plugin. Just remember if you're using modifiers that you need to list them in alphabetical order - so for example you'd do:

"ctrl+shift+c"

instead of:

"shift+ctrl+c"

I'm pretty sure it mentions that on the project page, but just make sure you remember that so it doesn't trip you up.

todd sharp's Gravatar Ah - here it is - on the about page:

http://code.google.com/p/js-hotkeys/wiki/about

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

Phillip Senn's Gravatar This reminds me of an interactive game I did back in college called Aster. It would check for a single key being pressed and act upon that.
Q: Is there a way to constantly be refreshing the screen.
Back in college, my program would sleep for a second, wake up, check the status of everything and go back to sleep.

yoal's Gravatar Great!