Skip to content

Instantly share code, notes, and snippets.

@lutsen
Last active December 27, 2015 17:19
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 lutsen/7361462 to your computer and use it in GitHub Desktop.
Save lutsen/7361462 to your computer and use it in GitHub Desktop.
Hilight a menu item when scrolling past the #id anchor using jQuery. A.k.a. ScrollSpy.
// The menu should have the id #menu
// ID's that have to work with this should have the class .scroll-anchor
function highlightMenuItem(anchor) {
var menu_item = $('#menu a[href="#/'+anchor+'"]');
if (menu_item && !menu_item.hasClass('active')) {
$('#menu .active').removeClass('active');
menu_item.addClass('active');
}
}
$(document).scroll(function() {
var viewport_top = $(document).scrollTop();
var viewport_bot = $(document).scrollTop()+$(window).height();
var top_element = false;
$('.scroll-anchor').each(function() {
if ($(this).css('display') !== 'none') {
var element_top = $(this).position().top;
if (element_top >= viewport_top && element_top < viewport_bot && (!top_element || top_element.position().top > element_top)) {
top_element = $(this);
return false;
}
}
});
if (top_element) {
var anchor = top_element.attr('id');
highlightMenuItem(anchor);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment