Tiny
Tiny

Reputation: 3

Javascript go to next and previous anchors on a document

I´m pretty profane in javascript.

I need a previous and next link that will just go to the previous or next #anchor.

All the anchors are divs with the same ID

This is what I have managed to do:

<script type="text/javascript">
$(document).ready(function() {

// Go to the next link
function goToNext() {

        window.location.href = .next('#display');
    }
}

// Go to the previous link
function goToPrev() {

        window.location.href = .prev('#display');
    }
}

</script>

then

<a href="javascript:goToNext()">next</a>
        <a href="javascript:goToPrev()" >Prev</a>

thanks!

Upvotes: 0

Views: 2913

Answers (2)

user113716
user113716

Reputation: 322492

It seems that you're using jQuery.

You can make your ID's to end with a number:

<div id="display_0">zero</div>
<div id="display_1">one</div>
<div id="display_2">two</div>
<div id="display_3">three</div>
<div id="display_4">four</div>
<div id="display_5">five</div>


<a href="#" id="prev">Prev</a>
<a href="#" id="next">Next</a>

Then bind functions to your next and prev links that increment/decrement an index, and set the location.hash to the ID plus the index.

$(document).ready(function() {

       // index to reference the next/prev display
    var i = 0;
       // get the total number of display sections
       //    where the ID starts with "display_"
    var len = $('div[id^="display_"]').length;


       // for next, increment the index, or reset to 0, and concatenate 
       //    it to "display_" and set it as the hash
    $('#next').click(function() {
        i = ++i % len;
        window.location.hash = "display_" + i;
        return false;
    });


       // for prev, if the index is 0, set it to the total length, then decrement
       //    it, concatenate it to "display_" and set it as the hash
    $('#prev').click(function() {
        if (!i) i = len;
        --i;
        window.location.hash = "display_" + i;
        return false;
    });

});

Upvotes: 2

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

Give each one a class, and find them based on that, then get the href property, which should be different.

document.location.hash = $("#"+document.location.hash).next(".myAnchors").attr("name");

<a id="number1" name="number1" href="#number1" class="myAnchors">first one</a>
<a id="number2" name="number2" href="#number2" class="myAnchors">second one</a>

Upvotes: 0

Related Questions