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) { $(".bio-panel:visible") .hide() .prev() .show(); return false; } // Right-arrow key event handler if (e.keyCode == 39) { $(".bio-panel:visible") .hide() .next() .show(); return false; } });