3

I was looking through answers for creating next and prev buttons that go through anchor points on a page, but couldn't find something I need. This one might of been close to what I wanted so I decided to use it as a starting point: How can I make a link go to the next anchor on the page without knowing anchor name?

I created a fiddle with the concept presented in that answer and tried to make it work together with bootstrap's scrollspy (detects the current section and anchor).

I have gotten this far: http://jsfiddle.net/gukne0oL/2/

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

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

The original answer targets the <a> tag, but in bootstrap's scrollspy, it adds the active class to the <li> tag wrapping the <a> tag. So I changed it accordingly... I feel like it's close? but I can't tell...

Can anyone help? Thank you!

Community
  • 1
  • 1
JuicyBB
  • 67
  • 2
  • 8

1 Answers1

3

Target active li, find the previous/next li, and drill down to the anchor.

http://jsfiddle.net/gukne0oL/9/

// Activate bootstrap scrollspy
$('body').scrollspy({ 
    target: '.navbar'
})

$('.next').click(function (e) {  
    var next = $('.navbar ul li.active').next().find('a').attr('href');
    $('html, body').animate({
        scrollTop: $(next).offset().top
    }, 500);
})

$('.previous').click(function (e) {
    var prev = $('.navbar ul li.active').prev().find('a').attr('href');
    $('html, body').animate({
        scrollTop: $(prev).offset().top
    }, 500);
})
mildse7en
  • 522
  • 1
  • 8
  • 20