Using the keyboard to navigate a web site [KeyboardFocus]
I’m beginning work on a project which requires users to be able to navigate the content of a web page using only the keyboard, and where switching focus using the standard method of tabbing is not an option either. To solve this problem, I’ve pieced together KeyboardFocus.
KeyboardFocus does one thing: Look through all elements on a web page with a given class name and make those elements selectable and clickable through the keyboard — using the arrow keys and the enter key.
Using the code is really quite easy:
- Add the CSS class name focusable to all the items you need to be addresseable with the keyboard.
- Add some CSS style for .focusable, for .focused and possibly for .hovered.
- Include the Prototype and KeyboardFocus scripts in your header.
- Add the line var kf = new KeyboardFocus(); somewhere in your code.
It could look something like this:
<html>
<head>
<script src="/script/prototype.js"></script>
<script src="keyboardfocus.js"></script>
<style type="text/css">
a {color:#06c; text-decoration:none;}
.focusable {border-bottom:1px solid #06c;}
a.focused {background-color:#06c; color:white;}
</style>
</head>
<body>
<ul>
<li>A link <a class="focusable"
href="http://www.google.com">Google</a></li>
<li>A <a class="focusable"
href="http://refresh.dk">different link</a></li>
<li>A <a href="http://www.yahoo.com">
non-focusable link</a></li>
<li>And something <a class="focusable"
href="http://xkcd.com/">completely different</a>.</li>
</ul>
<script>
new KeyboardFocus();
</script>
</body>
</html>
There’s also an example with random boxes.