November 28, 2015

Simple keyboard shortcuts for any website

I’m a huge fan of Gmail’s vim-inspired keyboard shortcuts. It’s been nice to see the adoption of keyboard shortcuts in other sites, but for most of the web, keyboard access remains completely ignored. I always just figured that it must be prohibitively difficult to implement keyboard shortcuts in a website, and so only the big players could do it. It turns out, however, that implementing keyboard shortcuts is embarassingly easy.

With no knowledge of javascript, I was able to add some simple keyboard navigation to this website (source repo). Though this website is built with Jekyll, this method would work on any website as it only uses some simple client-side javascript. I used the excellent Mousetrap library to handle keyboard input, and wrote some simple navigation commands in javascript.

I implemented two kinds of navigation in the spirit of Gmail: jumping and list navigation. (Note: I’m using the bind dictionary extension to bind multiple keys at once):


To get <g then h> style jumping, all you need is:

	'g h': function() {	window.location.href = "/"; },
	'g b': function() {	window.location.href = "/blog"; },
	'g r': function() {	window.location.href = "/research"; },

That’s it: incredibly simple.

Blog post navigation

Adding j/k navigation was a little more complicated. I wrote a function blogNav which takes a key press and does the following:

  • gets a list of all the post links (using their unique class, post-link)
  • gets the currently focused element
  • moves the link focus accordingly (‘j/k’), or launches the focused link (‘o’)

I also tweaked the CSS to change the color of focused links. To bind it in Mousetrap:

	'j': function() { blogNav('j'); },
	'k': function() { blogNav('k'); },
	'o': function() { blogNav('o'); }


Adding keyboard shortcuts to a website is surprisingly easy. It’s unfortunate that most web development is entirely focused on mouse input, relegating keyboard users to hacky extensions like vimium and pentadactyl. Hopefully Mousetrap can help more websites become keyboard friendly.

Spot an error? Have a suggestion? Submit an issue or contact me .