Handle keyboard shortcuts with jQuery

When you start building an application for the web, one of the features that almost always gets overlooked is accessibility. There are lots of plugins out there and most of them just ignore this. During the summer of 2011, I worked as a Google Summer of Code student for Inclusive Design Institute and the most unique thing about them was their focus on accessibility. I developed an image editor [source][<a href="https://pulkitgoyal.in/imageeditor/">demo</a>] component for the web. One of my focus during the development was to allow editing the images on the web without the use of mouse.

During this summer, I worked with NESCent on the development of jMatrixBrowse[source][<a href="https://pulkitgoyal.in/demo/jmatrixbrowse/" target="_blank">demo</a>]. This summer as well, I focused quite a lot on the keyboard accessibility for jMatrixBrowse. In this post, I’ll walk you through the process of creating keyboard shortcuts for jQuery plugins. And its really simple, thanks to jquery.hotkeys maintained by jeresig, the creator of jQuery.

The first step is to download the plugin. Its just one file. Get this. Now, its really simple to add keyboard shortcuts. Just include this script in the html. Here’s how you would now bind these in your js.

jQuery(document).bind('keydown', 'right', function(e) {
  // right arrow key pressed
jQuery(document).bind('keydown', 'left', function(e) {
  // left arrow key pressed
jQuery(document).bind('keydown', 'up', function(e) {
  // up arrow key pressed
jQuery(document).bind('keydown', 'down', function(e) {
  // down arrow key pressed
jQuery(document).bind('keydown', 'ctrl+up', function() {
  // ctrl + up arrow key pressed

Just add any combination of shortcuts that you want to bind to. Keep in mind not to use common browser shortcuts because the browsers might handle these shortcuts on their own and not pass them to your page. Firefox seems to be the most liberal in this regard and Safari the most restricting. So I would test the shortcuts in Safari to see if these are actually passed to my script.

Published 28 Aug 2012

I build mobile and web applications. Full Stack, Rails, React, Typescript, Kotlin, Swift
Pulkit Goyal on Twitter