Skip to content

Instantly share code, notes, and snippets.

@Laidlaw
Created June 6, 2013 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Laidlaw/5721873 to your computer and use it in GitHub Desktop.
Save Laidlaw/5721873 to your computer and use it in GitHub Desktop.
Navigation bar that becomes fixed once it reaches the top. Goes from 'chill' to 'fixed.' Also adds an "active" class to nav anchors.
var lastId,
scrollNav = $("#fixedMenu"),
menuItems = scrollNav.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top;
$('html, body').stop().animate({
scrollTop: offsetTop+10
}, 300 ,'easeInOutExpo');
e.preventDefault();
});
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
if(scrollTop > 130){
scrollNav.removeClass('chill').addClass('fixed');
} else if (scrollTop < 130){
scrollNav.removeClass('fixed').addClass('chill');
}
// Get id of current scroll item
var cur = scrollItems.map(function(){
if ($(this).offset().top < scrollTop) {
return this;
}
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#"+id+"]").parent().addClass("active");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment