public
Created

jQuery scroller, like bootstrap scrollspy

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
$(document).ready(function(){
var lastId, topMenu = $("#navbar-scroll"),
topMenuHeight = topMenu.outerHeight() + 150,
menuItems = topMenu.find("a"),
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
 
menuItems.click(function(e) {
var href = $(this).attr("href"),
topMenuHeight = topMenu.outerHeight() + 20,
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
 
$(window).scroll(function() {
var fromTop = $(this).scrollTop() + topMenuHeight;
 
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop) return this;
});
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
 
if (lastId !== id) {
lastId = id;
menuItems.parent().removeClass("active").end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.