Skip to content

Instantly share code, notes, and snippets.

@theskillwithin
Created April 6, 2016 21:21
Show Gist options
  • Save theskillwithin/9fb6b5eee2a3e7e015a2e38808f71d7b to your computer and use it in GitHub Desktop.
Save theskillwithin/9fb6b5eee2a3e7e015a2e38808f71d7b to your computer and use it in GitHub Desktop.
var highlightCurrentNavItem = {
getEachNavItem: function() {
hrefId: [];
$('nav li a').each(function() {
var that = $(this);
highlightCurrentNavItem.hrefId.push(that.attr('href'));
});
},
scroll: function() {
var current;
current = $.map(highlightCurrentNavItem.hrefId, function(a) {
var height = $(a).height();
var a = $(a).offset().top - $(window).scrollTop() + height; // detects what section id you are seeing based on scroll and top top
if (a >= 0) { // if its greater than 0 then its the page displaying or a lower page
return a;
} else {
return 999999; // negative value will be treated as 99999 so we can use the smallest totop number to determine current page
}
},
indexOfSmallest: function(b) {
return b.indexOf(Math.min.apply(Math, b));
},
init: function() {
$('nav a').css('color','red'); // Set the default color of the menu
highlightCurrentNavItem.getEachNavItem(); // Gets each item from the nav, grabs its anchor tag and adds to array hrefId
var page = indexOfSmallest(current); // get the section that is currently displaying
page = highlightCurrentNavItem.hrefId[page];
$('#fixed-nav li a').attr('style','');
$('#fixed-nav a[href$=' + page + ']').css('color','red');
$(document).scroll(function() {
highlightCurrentNavItem.scroll();
highlightCurrentNavItem.indexOfSmallest(current);
page = hrefId[page];
$('#fixed-nav li a').attr('style','');
$('#fixed-nav a[href$=' + page + ']').css('color','red');
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment