Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 877
dan Avatar asked Mar 14 '11 20:03

dan


2 Answers

$(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/

like image 81
Hussein Avatar answered Nov 06 '22 07:11

Hussein


OK...

var highlight = function(upOrDown){
    var highlighted = $("#daddyDiv > div.higlighted");

    if(highlighted[0] == null){
        //If nothing is highlighted, highlight the first child
        $("#daddyDiv > div:first").addClass("highlighted");
    } else {
        //Highlight the next thing
        if(upOrDown == "down" && highlighted.index() != $("#daddyDiv > div").length()){
            $("#daddyDiv > div").eq(highlighted.index()+1).addClass("highlighted");
            $("#daddyDiv > div.higlighted").removeClass("highlighted");
        } else if(upOrDown == "up" && highlighted.index() != 1){
            $("#daddyDiv > div").eq(highlighted.index()-1).addClass("highlighted");
            $("#daddyDiv > div.higlighted").removeClass("highlighted");
        }
    }
};

//Assuming you are using up/down buttons...

$("#upButton").click(function(){ highlight("up"); });
$("#downButton").click(function(){ highlight("down"); });

//Using the arrow keys...

$("body").keyup(function(e){
    if(e.keyCode == "40"){
        //Down key
        highlight("down");
    } else if(e.keyCode == "38"){
        //Up key
        highlight("down");
    }
});
like image 21
mattsven Avatar answered Nov 06 '22 05:11

mattsven