Friday, July 6, 2012

Another Short Cut - key.js

Keyboard shortcuts are a wheel that just begs for reinvention.  And being the sucker i am, i gave in and wrote me a new wheel just for that.

Like trigger.js, this is about better events and giving page controls control.  Jump below the gist for explanation:


This does two things:

  • allows keyboard shortcuts to be assigned in HTML
  • triggers namespaced, natural language 'key' events
<a key="alt-r" href="#reply">Reply</a>
<button key="home">Start Over</button>
$('#foo').on('key.ctrl-delete', Foo.deleteAll);
Both behaviors do not by default happen for most "plain" key events (roughly /[a-zA-Z0-9]/) unless you set key.all = true or add a 'key-all' class to your page's root tag (i.e. <html class="key-all">).

For the HTML shortcuts, key.js triggers 'click' events as appropriate. If you need a different event, add a trigger="different" and use trigger.js to translate the click.

key.js also provides a key() function to jQuery to let you trigger key events from javascript, as is quite necessary for testing your key events and shortcuts.

Obviously, if you look at the code, there are a great many keyCode values for which this wheel does not provide an English translation. At this point, 100% completeness seems both difficult (due to OS variation) and largely useless. Almost all "normal" keyboard shortcuts are accounted for, and any developer using this code can easily add more to key.codes. As with most of my wheels, this one is quite adjustable and extensible. Enjoy!