Skip to content

Instantly share code, notes, and snippets.

@misterbailey
Last active September 15, 2016 14:19
Show Gist options
  • Save misterbailey/a3669ca76f397e946d047c556b98f35e to your computer and use it in GitHub Desktop.
Save misterbailey/a3669ca76f397e946d047c556b98f35e to your computer and use it in GitHub Desktop.
A simple jQuery function to add a class of 'active' to the current navigation. Great for all those one-pagers out there
// Highlight Current Nav
$(document).ready(function() {
// Declare vars
var sections = $('section')
var nav = $('nav')
// When the window scrolls get the position
$(window).on('scroll', function() {
var curPos = $(this).scrollTop();
// An offset value based on window height
var offset = $(window).height() / 3;
// Get the top and bottom position of each section
sections.each(function() {
var top = $(this).offset().top - offset,
bottom = top + $(this).outerHeight();
// Conditional to work out if section is in correct place
if (curPos >= top && curPos <= bottom) {
// Remove active class from nav items and sections
nav.find('a').removeClass('active');
sections.removeClass('active');
// Add active class to current section and nav item
$(this).addClass('active');
nav.find('a[href="#' + $(this).attr('id') + '"]').addClass('active');
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment