Created
December 5, 2014 14:13
-
-
Save oguzhanaslan/ea57125099df86b48214 to your computer and use it in GitHub Desktop.
Sticky Header: Change Navigation Active Class on Page Scroll with jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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