Skip to content

Instantly share code, notes, and snippets.

@oguzhanaslan
Created December 5, 2014 14:13
Show Gist options
  • Save oguzhanaslan/ea57125099df86b48214 to your computer and use it in GitHub Desktop.
Save oguzhanaslan/ea57125099df86b48214 to your computer and use it in GitHub Desktop.
Sticky Header: Change Navigation Active Class on Page Scroll with jQuery
$(document).ready(function () {
$(document).on("scroll", onScroll);
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPosition = $(document).scrollTop();
$('nav a').each(function () {
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
$('nav ul li a').removeClass("active");
currentLink.addClass("active");
}
else{
currentLink.removeClass("active");
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment