Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of script.aculo.us, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Noko Time Tracking and Every Time Zone and write books like Retinafy.me.
   Want me to speak at your conference? Contact me!

Insanely easy keyboard shortcuts for your web apps — Keymaster.js

September 8th, 2011

For our next product Charm (an email support and CRM app) we’re going the all full-screen, real-time, highly interactive web app path, and using a lot of cool technologies, like Zepto.js, Backbone.js and CoffeeScript, to name a few.

As we believe that the details make the product, we’re also going to have keyboard shortcuts, so you can quickly navigate around the app without having to use your trackpad or mouse. After a short survey of what’s available for in-browser keyboard shortcuts (think Gmail or GitHub), for various reasons (other libs mostly depended on libraries or had too many/the wrong features) I decided to roll my own—and here it is!

Keymaster is a simple (100 LoC or so) micro-library for defining and dispatching keyboard shortcuts. It has no dependencies on any libraries so you can just drop it in your app and it will work, cross-browser.

// define short of 'a'
key('a', function(){ alert('you pressed a!') });

// returning false stops the event and prevents default browser events
key('ctrl+r', function(){ alert('stopped reload!'); return false });

// multiple shortcuts that do the same thing
key('⌘+r, ctrl+r', function(){ });

If you want to reuse the same shortcut for seperate areas in your single page app (we need this for Charm, so I added it in!), Keymaster supports switching between scopes. Use the key.setScope method to set scope.

// define shortcuts with a scope
key('o, enter', 'issues', function(){ /* do something */ });
key('o, enter', 'files', function(){ /* do something else */ });

// set the scope (only 'all' and 'issues' shortcuts will be honored)
key.setScope('issues');

Right now it’s in beta and we have a few known bugs, but overall it works really well already. If you’d like to contribute, you’ll find all info you need to get started in the Keymaster README on GitHub. Happy short-cutting!

P.S. Want to learn how to master the JavaScripts? Sign up for my virtual JavaScript Master Class! We still have some tickets left for our next one on September 15 ad 16. To sweeten the deal, I’m throwing in a coupon code just for you as my dear reader, use MIRAC50 to get $50 off any ticket!