Skip to content

Instantly share code, notes, and snippets.

@theskillwithin
Created April 5, 2016 22:46
Show Gist options
  • Save theskillwithin/ed0d8ce482c79742472b1ca5b5e739ce to your computer and use it in GitHub Desktop.
Save theskillwithin/ed0d8ce482c79742472b1ca5b5e739ce to your computer and use it in GitHub Desktop.
on a one page site this can be used to highlight the nav item of the current page.
var highlightCurrentNavItem {
hrefId: [];
current: var;
getEachNavItem: function() {
$('nav li a').each(function() {
var that = $(this);
hrefId.push(that.attr('href'));
});
},
Scroll: function() {
current = $.map(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)); // figures out the closest section
},
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 = 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