If no heading is in view, uses fallback

This commit is contained in:
Peter Dietrich
2012-07-19 17:41:52 +02:00
parent a33542b47c
commit d56fc820db

View File

@@ -26,33 +26,54 @@
})(jQuery); })(jQuery);
(function ($) { (function ($) {
//Add current view's highlighting to the navigation //Add current view's highlighting to the navigation
$(window).scroll(function() {
//console.log("They see me scrollin, they hatin");
//clear highlighting /** helper for highlighting */
var navLinks=$('.site-navigation a') function highlightNav(navLinks,id)
navLinks.removeClass("active"); {
navLinks.filter('[href="/#'+id+'"]').addClass("active");
}
//calc current viewport $(window).scroll(function() {
var viewTop = $(window).scrollTop(); //console.log("They see me scrollin, they hatin");
var viewBottom = viewTop + $(window).height();
//for all h1 and h2 elements, check if they are visible //clear highlighting
//performance tweak: stop each() after the first element is found to be behind view var navLinks = $('.site-navigation a');
$('h1, h2').each(function(i,e) { navLinks.removeClass("active");
//get element position;
var eTop = $(e).offset().top; //calc current viewport
var eBottom = eTop + $(e).height(); var viewTop = $(window).scrollTop();
if (eTop >= viewTop) { var viewBottom = viewTop + $(window).height();
if (eBottom <= viewBottom) {
//filter cached navLinks //for all h1 and h2 elements, check if they are visible
navLinks.filter('[href="/#'+e.id+'"]').addClass("active"); //performance tweak: stop each() after the first element is found to be behind view
} else { var previous = "";
//console.log("Start skipping test with "+e.id); var foundOne = false;
return false; var fallback = "";
} $('h1, h2').each(function(i,e) {
} //get element position;
}); var eTop = $(e).offset().top;
}); var eBottom = eTop + $(e).height();
var id=e.id;
if (eTop >= viewTop) {
//if we are passed the view and no heading was highlighted yet, store previous one as fallback
if (! foundOne) {
fallback=previous;
}
if (eBottom <= viewBottom) {
highlightNav(navLinks, id);
foundOne = true;
} else {
return false; //break the each(), the rest is below
}
}
previous=id;
});
//no h1/h2 is in the viewport, so highlight the last one above
if (! foundOne) {
highlightNav(navLinks, fallback);
}
});
})(jQuery); })(jQuery);