Why jQuery Rocks – Reason #41

I’ve spent much of my afternoon looking at implementing an elegant solution to enable a degree of keyboard navigation for what is effectively an HTML slideshow.

I’d wired up a keypress event handler, but the tricky part actually turned out to be how to hide the current element and display the next (or preceding) one. Getting it to work on two slides was easy because you have an either/or situation; but once the model grows beyond that, it becomes necessary to keep a stateful record of the current position so it doesn’t get lost.

Now, jQuery has a ton of built in tools that will allow you to navigate DOM elements to your hearts content. But after banging on a bunch of these solutions for a couple hours, I realized that jQuery has all the functionality I needed built-in to its API.

One of the niftiest aspects of the query selector syntax is the pseudo-selector. Just like CSS implements a:hover and a:visited, jQuery implements mySelector:visible. That’s is! It’s so easy.

$(document).keypress(function(e) {
	// Left-arrow key event handler
	if (e.keyCode == 37) {
		return false;
	// Right-arrow key event handler
	if (e.keyCode == 39) {
		return false;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.