I have an input field and a div with four operating systems. When the cursor is in the input field and you press the down arrow, it should go down cycling through each OS div when you press down. The issue is when you get to the last div, and press down, it should go back to the first div on top, however, it seems to “skip” to a non existent div on the first keyboard press down, but if you press it a second time, it goes back to the first div as it should. How can I make it not “skip” and go directly to the first div in the list by pressing down from the last div in the list? Any idea on how to get this to work correctly?
Here is the HTML:
<input id="system" value="" />
<div id="system-drop">
<div class="os active">Mac</div>
<div class="os">Windows</div>
<div class="os">Linux</div>
<div class="os">Other</div>
</div>
Here is the jQuery:
$("#system").live('keyup',function(e){
var curr = $('#system-drop').find('.active');
if(e.keyCode == 40 || e.charCode == 40){
if(curr.length){
$('.os.active').removeClass('active');
$(curr).next().addClass('active');
} else{
$('#system-drop div:first-child').addClass('active');
}
}
});
Here is the fiddle:
http://jsfiddle.net/TF6Rb/771/
The
curr.lengthwas not zero untilcur.next().length = 0. Which means, when the cursor is at the last div, the cur.length is still 1 but there is nocur.next().Modified jsFiddle here
Change your condition like below and it should work,