Navigate to NEXT / PREV buttons with Bootstrap ScrollSpy
I was going through the answers for creating next and prev buttons that looked at anchor points on the page but couldn't find something I needed. This one might be close to what I wanted, so I decided to use it as a starting point: How can I make the link go to the next anchor on the page without knowing the name of the anchor?
I created a fiddle with the concept presented in this answer and tried to get it to work alongside bootstrap scrollspy (detects current section and anchor).
I got 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 tag <a>
, but in bootstrap scrollspy it adds a class active
to the tag <li>
while wrapping the tag <a>
. So I changed it accordingly ... I feel like it's close? but I can't tell ...
Can anyone please help? Thank!
source to share
Set up active li, find previous / next li and go to binding.
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);
})
source to share