Skip to content

Instantly share code, notes, and snippets.

@alfahami
Created March 11, 2020 18:02
Show Gist options
  • Save alfahami/c2cd2e27ea9057c1f1e8000a137ac114 to your computer and use it in GitHub Desktop.
Save alfahami/c2cd2e27ea9057c1f1e8000a137ac114 to your computer and use it in GitHub Desktop.
highlight navbar item menu on scroll
if ($) {
// Basice Code keep it
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$('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 - 65
},
800
);
});
});
// Use Your Class or ID For Selection
function onScroll() {
var scrollPos = $(document).scrollTop() + 60;
$("#left-nav ul li a").each(function() {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
var nav = $(".item-nav");
if (nav.length) {
if (
refElement.position().top <= scrollPos &&
refElement.position().top + refElement.height() > (scrollPos)
) {
$("#left-nav.item-nav ul li").removeClass("active");
currLink.addClass("active");
}
else {
currLink.removeClass("active");
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment