Does somebody know an solution with jquery to navigate through an list with the arrow keys(up,down)?
If i have an list for example, with links:
<a href="#">First Link</a>
<p>
<a href="#">Second Link</a>
<p>
<a href="#">Third Link</a>
<p>
<a href="#">Fourth Link</a>
<p>
It would be nice if the user sees where he actually navigates with an hover effect:
a:hover{color:blue}
Thanks! To experiment: http://jsfiddle.net/ZBn7r/1/
Replace hover by focus.
Then, you can move the focus to the next and previous links with jQuery like that :
$(document).keydown(
function(e)
{
if($('a:focus').length==0){$('a').first().focus();}
if (e.keyCode == 39) {
$("a:focus").next().focus();
}
if (e.keyCode == 37) {
$("a:focus").prev().focus();
}
}
);
Updated fiddle : http://jsfiddle.net/ZBn7r/2/
fully working code snippet tested in jsfiddle link
HTML
<ul>
<li><a href="#">First Link</a></li>
<li> <a href="#">Second Link</a></li>
<li> <a href="#">Third Link</a></li>
</ul>
CSS
li.selected {background:yellow}
a:hover{color:blue}
a {
color:inherit;
text-decoration: none;
}
ul
{
list-style-type: none;
}
JS
var li = $('li');
var liSelected;
$(window).keydown(function(e){
if(e.which === 40){
if(liSelected){
liSelected.removeClass('selected');
next = liSelected.next();
if(next.length > 0){
liSelected = next.addClass('selected');
}else{
liSelected = li.eq(0).addClass('selected');
}
}else{
liSelected = li.eq(0).addClass('selected');
}
}else if(e.which === 38){
if(liSelected){
liSelected.removeClass('selected');
next = liSelected.prev();
if(next.length > 0){
liSelected = next.addClass('selected');
}else{
liSelected = li.last().addClass('selected');
}
}else{
liSelected = li.last().addClass('selected');
}
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.