I Added Keyboard Navigation to my Site

by Rob Larsen

Kind of a fun little exercise. Now I just need to figure out a nice way to hint to people that they can navigate with the keyboard.

Check it out. Start here and hit your right arrow key until you start to see the same things twice.

Based on shortcuts.js

R.nav = {
	init: function(){	
		var bod = document.body;
//are we on a gallery page?
		if (bod.id == "detail" && bod.className == "art") {
//add an event
//use your library method of choice, please
//we don't want to mess things up for other people
			document.onkeydown= R.nav.navigate ;
		} 
	},
	navigate : function(e) {
//normalize the event that comes in
//it's either the first argument to the function
//or it's window.event
		e = e || window.event;
		var obj;
//test to see what object initiated the event
		if(e.target) {
			obj=e.target;
		}
		else if (e.srcElement) {
			obj=e.srcElement;
		}
//was it a text node?
		if(obj.nodeType==3) {
			obj=obj.parentNode;
		}
//if it was an input or textarea, we want people to be able to
//use the arrow keys, clearly.
		if(obj.tagName == 'INPUT' || obj.tagName == 'TEXTAREA') {
			return;
		}
//get the numeric code of the key pressed
		if (e.keyCode) {
			code = e.keyCode;
		}
//ie doesn't understand event.which, apparently
		else if (e.which) {
			code = e.which;
		}
//test the code to see if it's a right or left arrow
//and navigate accordingly. The ids prev and next
//match the rel attributes, by the way
		if (code == 37){
			document.location.href=document.getElementById("prev").href;
		} else if (code ==39){
			document.location.href=document.getElementById("next").href; 
		}
	}
};

Leave a Reply