Skip to content

Instantly share code, notes, and snippets.

@johnie
Created August 11, 2013 15:19
Show Gist options
  • Save johnie/6205328 to your computer and use it in GitHub Desktop.
Save johnie/6205328 to your computer and use it in GitHub Desktop.
Simple scrollspy
var lastId,
topMenu = $("#Navigation"),
topMenuHeight = topMenu.outerHeight()+0,
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"),
offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 600);
e.preventDefault();
});
function highlightNav() {
var fromTop = $(window).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 : "";
console.log("id",id);
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.removeClass("is-Current")
.filter("[href=#"+id+"]").addClass("is-Current");
}
}
highlightNav();
$(window).scroll( highlightNav );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment