Web application hotkeys with Javascript

Technology

It’s unfortunate, but there are only a few sites that have done a good job of enhancing the user experience with hotkey support. In searching for the easiest way to do this in my own applications, I stumbled across the Hotkeys plugin for jQuery. In typical jQuery form it lets you do something moderately complicated, like capturing keyboard events, with a single line of Javascript code. You use the hotkeys.add method to bind a keyboard event to a callback function and the hotkeys.remove method to remove the handler.

Here’s an example that will create an alert box when you press control-c:

$.hotkeys.add('Ctrl+c', function(){ alert('ctrl-c pressed');});

You remove the handler like this:

$.hotkeys.remove('Ctrl+c');

hotkeys.add can also has a 3 parameter evocation: hotkeys.add(key, options, handler). The options parameter is just an associative array which you can use to pass options such as the target DOM path or the type of key press event (keyup or keydown). The key parameter is a string representing the key combination. Instead of using scan codes, you send in the names of the key combination, such as “a”, “Shift+b”, “f9”, or “pageup”. It’s really that easy.

Javascript jQuery Hotkeys Plugin
Using jQuery Hotkeys

What will the next generation of Make: look like? We’re inviting you to shape the future by investing in Make:. By becoming an investor, you help decide what’s next. The future of Make: is in your hands. Learn More.

Tagged
Discuss this article with the rest of the community on our Discord server!

ADVERTISEMENT

Escape to an island of imagination + innovation as Maker Faire Bay Area returns for its 16th iteration!

Prices Increase in....

Days
Hours
Minutes
Seconds
FEEDBACK