How can I find the next or previous <a>
regardless of where it is placed in DOM?
When I press key down, I want to highlight the next <a>
, when I press up I want to highlight the previous one regardless of where it is nested in DOM.
<div id="info">
<span><a href="#info">How can I get this when pressing up?</a></span>
<a class="focus" href="#home">I'm here - and will either press up or down</a>
<div>
<ul>
<li><a href="#foo">How can I get this when pressing down?</a></li>
<li><a href="#bar">Another link</a></li>
</ul>
</div>
</div>
I have tried next()
, nextAll()
, prev()
and prevAll()
with out luck.
This is what I have so far
$(document).keypress(e){
var keyCode = e.keyCode;
switch (keyCode) {
case 38:
e.preventDefault();
$("body").trigger('nav', 'up');
break;
case 40:
e.preventDefault();
$("body").trigger('nav', 'down');
break;
}
$("body").bind('nav', function(direction){
var currentLink = $(".focus").first();
if(direction === 'up'){
var prevLink = ???
} else if (direction === 'down'){
var nextLink = ???
}
});
});
This is a basic code i write on jsfiddle, you can start with.
http://jsfiddle.net/sabri/skXZT/10/
Javascript
var allLink = jQuery('a');
var currentHighLight = allLink.filter('.highlight');
$('body').keyup(function(event) {
index = allLink.index(currentHighLight);
currentHighLight.removeClass('highlight');
if (event.which == 38) {
allLink.eq(index-1).addClass('highlight')
} else if (event.which == 40) {
allLink.eq(index+1).addClass('highlight')
}
currentHighLight = allLink.filter('.highlight');
});
on down key, do:
if($('a[cur="1"]').length==0) {
$('a:first').attr('cur', "1");
$('a:first').addClass('highlight');
return false;
}
var previous = null, next = null;
$('a').each(function() {
if(previous!=null && $(previous).attr('cur')=='1') {
$(previous).removeAttr('cur');
$(previous).removeClass('highlight');
$(this).attr('cur', "1");
$(this).addClass('highlight');
return false;
}
previous = this;
}
on up key, do:
if($('a[cur="1"]').length==0) {
$('a:first').attr('cur', "1");
$('a:first').addClass('highlight');
return false;
}
var previous = null;
$('a').each(function() {
if($(this).attr('cur')=='1') {
$(this).removeAttr('cur');
$(this).removeClass('highlight');
if(previous!=null) {
$(this).attr('cur', "1");
$(this).addClass('highlight');
}
else {
$('a:last').attr('cur', "1");
$('a:last').addClass('highlight');
}
return false;
}
previous = this;
}
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.