detecting the last list item in jquery/javascript
-
25-09-2019 - |
Question
I have a set of tab (main-tabs) on a website and each tab has another set of tabs (sub-tabs). I want to use arrow keys on a keyboard to navigate the tabs, instead of a mouse.
These tabs are just HTML list items <li>
When I reach the last sub-tab with the arrow key, I want it to go back to the next main tab so it can display its own sub-tabs, and carry on the navigation inside it.
My question is, how can I detect, in jQuery/javascript, when I've reached the last list item (tab) using the arrow keys i.e. the right arrow key?
Many Thanks
Solution
You might be able to use either the :last or :last-child selectors in jQuery. Depending on how your <li>
tags are nested, you might also have to use the children() function along with it.
For example, let's say you have the following markup:
<ul id="nav">
<li>List item</li>
<li>List item with sub items
<ul>
<li>Sub list item</li>
</ul>
</li>
</ul>
This would select the last top-level <li>
$('ul#nav > li:last').css('border', '1px solid red');
This would select the last <li>
traversing the DOM downward. In this case it's the <li>
with text "Sub list item"
$('ul#nav li:last').css('border', '1px solid red');
This would select any <li>
tags that are the last child of their parent
$('ul#nav li:last-child').css('border', '1px solid red');
OTHER TIPS
var maintabs = $('.maintab'),
active_maintab_eq = 0,
active_subtab_number = 1;
$(document).keyup( function(e){
if (e.which == 39) {
// right arrow key pressed
if ( active_subtab_number == maintabs.eq(active_maintab_eq).find('li').length ) {
// go to next main-tab
// and reset active sub-tab counter
++active_maintab_eq;
active_subtab_number = 1;
} else {
++active_subtab_number;
}
}
});
Some thing like this, I guess.
You can use .length
to find out if a jQuery selector found anything:
var nextSubTab = $(currentSubTab).next("li");
if (nextSubTab.length == 0) {
// oops, end of this tab, switch to next tab
}