Skip to content

Instantly share code, notes, and snippets.

@jaredatch
Created August 5, 2015 20:45
Show Gist options
  • Select an option

  • Save jaredatch/44b68b2b79e3ab9f8817 to your computer and use it in GitHub Desktop.

Select an option

Save jaredatch/44b68b2b79e3ab9f8817 to your computer and use it in GitHub Desktop.
Simple jQuery scrollspy
(function ($) {
/**
* Scroll spy
*/
// Cache selectors
var lastId,
scrollSpyMenu = $(".process-nav");
scrollSpyMenuHeight = scrollSpyMenu.outerHeight()+55;
scrollSpyMenuItems = scrollSpyMenu.find('a');
scrollItems = scrollSpyMenuItems.map(function(){
var item = $($(this).attr('href'));
if (item.length) {
return item;
}
});
// Bind to scroll
$(window).scroll(function(){
var fromTop = $(this).scrollTop()+scrollSpyMenuHeight;
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;
scrollSpyMenuItems.removeClass('active').filter("[href=#"+id+"]").addClass("active");
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment