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

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

ADVERTISEMENT

Maker Faire Bay Area 2023 - Mare Island, CA

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

Buy Tickets today! SAVE 15% and lock-in your preferred date(s).

FEEDBACK