I have a hierarchy with links nested in list element like this:
<ul>
<li><a href="#">Page 1</a>
<ul>
<li><a href="#">Page 1.1</a></li>
<li><a href="#">Page 1.2</a>
<ul>
<li><a href="#">Page 1.2.1</a></li>
<li><a href="#">Page 1.2.2</a></li>
</ul>
</li>
<li><a href="#">Page 1.3</a></li>
</ul>
</li>
<li><a href="#">Page 2</a>
<ul>
<li><a href="#">Page 2.1</a></li>
<li><a href="#">Page 2.2</a></li>
</ul>
</li>
<li><a href="#">Page 3</a>
<ul>
<li><a href="#">Page 3.1</a>
<ul>
<li><a href="#">Page 3.1.1</a></li>
<li><a href="#">Page 3.1.2</a></li>
</ul>
<li><a href="#">Page 3.2</a></li>
<li><a href="#">Page 3.3</a></li>
<ul>
<li><a href="#">Page 3.1.1</a></li>
<li><a href="#">Page 3.1.2</a></li>
</ul>
</li>
</ul>
</li>
</ul>
Basically just a sitemap. But I want to make next and previous links with jQuery, which finds the active page you're on (probably by checking for a class), and finding the previous and next anchor element (taking no regards of the hierarchy). I've tried with next()
, previous()
and find()
but can't seem to get it to work.
What is the easiest way to get the anchor elements before and after the current one?
var selected = $("a.selected");
var anchors = $("a");
var pos = anchors.index(selected);
var next = anchors.get(pos+1);
var prev = anchors.get(pos-1);
Assuming the <a>
for the current page has class="current"
, then you can do this to find the flattened index of the current page within the sitemap:
// Get current anchor
var currentA = $("a.current");
// Get array of all anchors in sitemap
var anchors = $("ul a"); // (would be better if you gave the ul an id)
// Find the index of the current anchor, within the (flattened) sitemap
var i = anchors.index(currentA);
I split the above into 3 lines for illustrative purposes, but you can shorten the above code to:
var i = $("ul a").index($("a.current"));
Then you can write functions to navigate the page to the next and prev links:
// Go to the next link
function goToNext() {
if (i + 1 < anchors.length) {
window.location.href = anchors[i + 1].href;
}
}
// Go to the previous link
function goToPrev() {
if (i > 0) {
window.location.href = anchors[i - 1].href;
}
}
Finally, attach these functions to your next and prev anchors:
$("a.next").click(goToNext);
$("a.prev").click(goToPrev);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With