From d56fc820db7007b6cc9ab5b98e2ba268f8304ee3 Mon Sep 17 00:00:00 2001 From: Peter Dietrich Date: Thu, 19 Jul 2012 17:41:52 +0200 Subject: [PATCH] If no heading is in view, uses fallback --- scripts/setup.js | 73 +++++++++++++++++++++++++++++++----------------- 1 file changed, 47 insertions(+), 26 deletions(-) diff --git a/scripts/setup.js b/scripts/setup.js index 23ef869..49695dc 100644 --- a/scripts/setup.js +++ b/scripts/setup.js @@ -26,33 +26,54 @@ })(jQuery); (function ($) { - //Add current view's highlighting to the navigation - $(window).scroll(function() { - //console.log("They see me scrollin, they hatin"); + //Add current view's highlighting to the navigation + + /** helper for highlighting */ + function highlightNav(navLinks,id) + { + navLinks.filter('[href="/#'+id+'"]').addClass("active"); + } - //clear highlighting - var navLinks=$('.site-navigation a') - navLinks.removeClass("active"); + $(window).scroll(function() { + //console.log("They see me scrollin, they hatin"); - //calc current viewport - var viewTop = $(window).scrollTop(); - var viewBottom = viewTop + $(window).height(); + //clear highlighting + var navLinks = $('.site-navigation a'); + navLinks.removeClass("active"); - //for all h1 and h2 elements, check if they are visible - //performance tweak: stop each() after the first element is found to be behind view - $('h1, h2').each(function(i,e) { - //get element position; - var eTop = $(e).offset().top; - var eBottom = eTop + $(e).height(); - if (eTop >= viewTop) { - if (eBottom <= viewBottom) { - //filter cached navLinks - navLinks.filter('[href="/#'+e.id+'"]').addClass("active"); - } else { - //console.log("Start skipping test with "+e.id); - return false; - } - } - }); - }); + //calc current viewport + var viewTop = $(window).scrollTop(); + var viewBottom = viewTop + $(window).height(); + + //for all h1 and h2 elements, check if they are visible + //performance tweak: stop each() after the first element is found to be behind view + var previous = ""; + var foundOne = 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); +