I am navigating within my app with the help of keyboard arrow keys. In my app, some dynamically set elements display vertically within a list. So far, the code below allows for horizontal navigation within each dynamically set <li>
and vertical navigation throughout all dynamically set <li>
. But there's a glitch: I can't seem to navigate vertically throughout all available links (element target focus is not a destination link).
IMPORTANT: Your solution must provide code that is oblivious to the amount of elements or their type, or their classes, within each <li>
. Therefore, to keep code minimal and flexible, your solution must only refer to the index position of the source element that is focused, and target a destination element that has the same index as source (source element index greater than available destination element index must target last destination element) :
<ul>
<li><div class="card"><a href="javascript:void(0)" class="card-title">My Card</a><button class="card-export">CE</button><button class="vc-target">CT</button></div></li>
<li><div class="card"><a href="javascript:void(0)" class="card-title">My Card</a><button class="card-export">CE</button><button class="vc-target">CT</button></div></li>
<li><div class="card"><a href="javascript:void(0)" class="card-title">My Card</a><button class="card-export">CE</button><button class="vc-target">CT</button></div></li>
</ul>
$(function(){
$('.card').on('keydown', function(e){
var isfocus = $(this).find('a:focus,button:focus');
var isfocusindex = $(this).find('a:focus,button:focus').index()-1;
var afocus = $(this).find('a:focus');
var bfocuslast = $(this).find('button:last:focus');
if ( e.which == 37 ) { // Left arrowkey
isfocus.prev('button,a').focus();
afocus.parent('div').find('button:last').focus();
}
if ( e.which == 39 ) { // right arrowkey
isfocus.next('button').focus();
bfocuslast.parent('div').find('a:first').focus();
}
if ( e.which == 40 ) { // down arrowkey
isfocus.parent('div').parent('li').next('li').find('div').find('a:eq('+isfocusindex+'),button:eq('+isfocusindex+')').focus();
}
if ( e.which == 38 ) { // UP arrowkey
isfocus.parent('div').parent('li').prev('li').find('div').find('a:eq('+isfocusindex+'),button:eq('+isfocusindex+')').focus();
}
});
});