How do you make up and down arrows highlight items in a list? (jQuery)

dan picture dan · Mar 14, 2011 · Viewed 8.2k times · Source

I have a stack of <DIV> siblings and I want to let the user use the up and down arrows to move up and down the list and "highlight" an item. Only one item should be highlighted at any given moment.

What's the easiest way to do this?

Answer

Hussein picture Hussein · Mar 14, 2011
$(document).keyup(function(e) {
    var $hlight = $('div.hlight'), $div = $('div');
    if (e.keyCode == 40) {
        $hlight.removeClass('hlight').next().addClass('hlight');
        if ($hlight.next().length == 0) {
            $div.eq(0).addClass('hlight')
        }
    } else if (e.keyCode === 38) {
        $hlight.removeClass('hlight').prev().addClass('hlight');
        if ($hlight.prev().length == 0) {
            $div.eq(-1).addClass('hlight')
        }
    }
})

Check working example at http://jsfiddle.net/wMdML/8/