Skip to content

Instantly share code, notes, and snippets.

@rwaldron
Created October 12, 2010 19:55
Show Gist options
  • Save rwaldron/622795 to your computer and use it in GitHub Desktop.
Save rwaldron/622795 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>List navigation</title>
<style>
.selected {
background: yellow;
}
</style>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="linav.js"></script>
</head>
<body>
<ul>
<li> one </li>
<li> two </li>
<li> three </li>
<li> four </li>
</ul>
</body>
</html>
$(function () {
var $li = $('li'),
getIndex = function ( context, selector ) {
for ( var i = 0, len = context.length; i < len; i++ ) {
if ( $(context[i]).filter(selector).length ) {
return i;
}
}
};
$li.bind('click', function () {
var $this = $(this);
$li.removeClass('selected');
$this.toggleClass('selected');
});
$(document).bind('keydown', function (e) {
var next, current;
if ( [40, 38].indexOf(e.which) > -1 &&
$li.filter('.selected').length ) {
current = getIndex( $li, '.selected');
if ( e.which === 38 ) {
next = ( ( (current - 1) < 0 ) &&
$li.length - 1 ) || current -1;
}
if ( e.which === 40 ) {
next = ( ( current === $li.length ) &&
current - $li.length ) || current +1;
if ( next === $li.length ) {
next = 0;
}
}
$( $li[next] ).trigger('click');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment