How can I make a link go to the next anchor on the page without knowing the name of the anchor?

I have a button at the top of the page and I want to code it to go to the next anchor no matter what it is. Actually, I want to make next / previous buttons to go to next and previous anchors. This button is on a static frame to ideally scroll to the rest of the page.

Any suggestions would be great. Again I won't know what an anchor is, it's more like navigating a chapter with a generic button.

It seems like finding the next anchor object in the dom and going there should be doable, but I'm not screeching into jquery or javascript for that.

+1


source to share


2 answers


var index = -1;

$('.next').click(function() {
   index++;
   $(window).scrollTop($('a').eq(index).position().top);

});
$('.previous').click(function() {
   index--;
   if(index < 0) { index = 0;}

   $(window).scrollTop($('a').eq(index).position().top);
});

      



+1


source


A good solution would be to set the "current" anchor using a class (maybe hardcoded - the first anchor on the page with class = "current") and then use jquery to navigate through the dom and select the next or previous anchor. Assuming you have next and previous buttons, you can do something like:



<script type="text/javascript">

  $('.next').click(function(e){
    e.preventDefault();
    var current_anchor = $('a.current');
    var next_anchor = current.next('a');
    $('body').animate({scrollTop:next_anchor.offset().top});
  })

  $('.previous').click(function(e){
    e.preventDefault();
    var current_anchor = $('a.current');
    var previous_anchor = current.prev('a');
    $('body').animate({scrollTop:previous_anchor.offset().top});
  })

</script>

      

0


source







All Articles