I have a list that has keyboard support for navigation. However, there is additional jiggery pokery (which isn’t inlcuded in this example) that shows and hides items in the list. After items are hidden the keyboard navigation needs to continue functioning but only for visible items.
I’ve got this working great. The problem occurs when the last visible item is the current item and then a user presses down again. The current class is removed and it tries to move on to an item that doesn’t exist. The same thing happens when navigating up.
How can I navigate visible items only and get it to stop on the first and last visible items?
jQuery(document).keydown(function(e) {
e.preventDefault();
if (e.keyCode == 38) { // Capture Arrow Up key 38
var currentItem = jQuery(".options").children("li.current").removeClass("current").prevAll(':visible:first').addClass("current");
} else if (e.keyCode == 40) { // Capture Arrow Down key 40
var currentItem = jQuery(".options").children("li.current").removeClass("current").nextAll(':visible:first').addClass("current");
}
});
.current {
border: solid 1px #f60 !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="options">
<li class="current"><a href="#"><span>WW Portfolio Regions</span><span class="hidden">0</span></a>
</li>
<li><a href="#"><span>EMEA</span><span class="hidden">1</span></a>
</li>
<li><a href="#"><span>Americas</span><span class="hidden">2</span></a>
</li>
<li><a href="#"><span>AP</span><span class="hidden">3</span></a>
</li>
<li><a href="#"><span>NE IOT</span><span class="hidden">4</span></a>
</li>
<li><a href="#"><span>SW IOT</span><span class="hidden">5</span></a>
</li>
<li><a href="#"><span>CCE IOT</span><span class="hidden">6</span></a>
</li>
<li><a href="#"><span>MEA IOT</span><span class="hidden">7</span></a>
</li>
</ul>
If the current element is the last one, nextAll() will return an empty jQuery object.You can test for that case and only remove the class from the current element if it’s not the first (or last) one: