Skip to content

Instantly share code, notes, and snippets.

@mintchaos
Created April 20, 2011 17:43
Show Gist options
  • Save mintchaos/932105 to your computer and use it in GitHub Desktop.
Save mintchaos/932105 to your computer and use it in GitHub Desktop.
// This returns a list of strings of everything my nav links to.
// Like this ['#weddings', '#contact', '#etc']
var sections = $.map($("#main-header a"), function(e){ var h = $(e).attr('href'); if (h.length > 1) { return h } });
// This turns that list into a jquery collection of the linked elements.
sections = $(sections.join())
function activateNav(e) {
// kill all active states
$('#main-header li').removeClass('active');
sections.each( function() {
var id = this.id
var totalHeight = document.body.offsetHeight;
var visibleHeight = document.documentElement.clientHeight;
var scrollTop = $(window).scrollTop();
// My in view check. Top of the page is at or past the element.
// And then make sure we haven't scrolled past it entirely.
if ( scrollTop >= $(this).offset().top &&
scrollTop < $(this).offset().top + $(this).outerHeight(true)
) {
// make it active.
$('#main-header [href="#' + id +'"]').parent().addClass('active');
};
// Cheat and if we're at the very bottom show that #contact is active.
if (totalHeight <= scrollTop + visibleHeight) {
$('#main-header li').removeClass('active');
$('#main-header [href="#contact"]').parent().addClass('active');
}
});
}
// Listen to everything!
$(window).resize(activateNav);
$(window).scroll(activateNav);
$(window).ready(activateNav);
$("#main-header").click(activateNav);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment