Keyboard navigation using MooTools and jQuery

Oct 21, 01:38 AM

One of my favorite easter eggs in blogs and page content is when the arrow keys produce the same effect as clicking on the next or previous link/button/slider/widget/doodad (such as the Huffington Post's load-on-demand picture slider in the silly article Top 10 Party Schools). Here's a great article by Remy Sharp about using the arrow keys to control a slider. But because I don’t see this behavior enough, here’s how you could go about it:

  1. Give your “next” and “previous” links unique IDs.
  2. Add a handler to the document that listens for keydown events.

Super simple.

An example using MooTools:

Give your previous-page link an ID of “pnav_prev” and the next-page link an ID of “pnav_next”. Then at some point after the DOM has finished loading, add this JavaScript:

// listen for left & right arrows
document.addEvent('keydown', function(e) {
        // left = prev
	if (e.code == '37') location.href=$('pnav_prev')['href'];

	// right = next
	if (e.code == '39') location.href=$('pnav_next')['href'];
});

In jQuery:

Doing this is jQuery would be nearly (though not exactly) the same thing:

// listen for left & right arrows
$(document).keydown(function (e) {
  // left = prev
  if (e.keyCode == '37') location.href = $('#pnav_prev')[0]['href'];

  // right = next
  if (e.keyCode == '39') location.href = $('#pnav_next')[0]['href'];
});

As a matter of fact, that's the exact code this site's using (more or less: I decided to select the link based on its rel attribute).

You may be wondering why I’m choosing to fiddle with setting the [window.]location instead of just triggering the link’s click event. In jQuery at least, $('#pnav_next').click() simply won’t work. $('#pnav_next').trigger('click') works if you set up a click handler first (what I’ll call the bind-and-trigger method). For simple press-right-goto-next-article behavior, this would be overkill. If there were a stack of click events on that link that needed to be fired, using that method would be worth it.

FYI: using the arrow keys this way could have negative consequences. For instance: if the page had a form with radio buttons and/or checkboxes, this would definitely be undesirable behavior. And how would you handle the scenario in which you have a multi-page article? And so forth.

I couldn't find any instances of sites using this in for next/previous links, but I'm positive they're out there. Let me know if you find them. In the meantime, consider using this technique in your own projects. It's not rocket science, and I for one would appreciate it!

Bookmark and Share
 

Comment

  1. Lovely site! I am loving it!! Will be back later to read some more. I am taking your feeds also dd1

    flash chat · Jan 30, 07:04 AM · #

|

Valid XHTML 1.1 Valid CSS
             © 2008, garvin