1

This is a simple requirement and I cannot make it work.

I simply want to navigate through a using arrow keys.Also I want to detect when a arrow key is pressed on a LI.However I cannot navigate with arrows- nor does my keydown event fire.

       <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("li,a").keydown(function () {
                    alert("kd");
                });
            });
        </script>
    </head>
    <body>



<div>
        <input type="text" />
        <ul id="sbOptions_54514054" class="sbOptions" style="">
            <li><a href="#-1" rel="-1">--Select one--</a></li>
            <li><a href="#2" rel="2">Windows</a></li>
            <li><a href="#1" rel="1">Siding</a></li>
            <li><a href="#7" rel="7">Roofing</a></li>
        </ul>
    </div>
Charles
  • 50,943
  • 13
  • 104
  • 142
josephj1989
  • 9,509
  • 9
  • 48
  • 70

1 Answers1

7

How about something like this jsFiddle?

Basically it maintains a simple index of which list item is currently selected. The up and down arrow keys are bound to the keydown event and if someone presses the up arrow at the top of the list, the top item stays selected and vice-versa.

var chosen = "";
$(document).keydown(function(e){ // 38-up, 40-down
    if (e.keyCode == 40) { 
        if(chosen === "") {
            chosen = 0;
        } else if((chosen+1) < $('li').length) {
            chosen++; 
        }
        $('li').removeClass('selected');
        $('li:eq('+chosen+')').addClass('selected');
        return false;
    }
    if (e.keyCode == 38) { 
        if(chosen === "") {
            chosen = 0;
        } else if(chosen > 0) {
            chosen--;            
        }
        $('li').removeClass('selected');
        $('li:eq('+chosen+')').addClass('selected');
        return false;
    }
});
j08691
  • 204,283
  • 31
  • 260
  • 272