Skip to content

Instantly share code, notes, and snippets.

@webhasan
Last active June 11, 2021 04:03
Show Gist options
  • Save webhasan/cad07710fe04b88b4467 to your computer and use it in GitHub Desktop.
Save webhasan/cad07710fe04b88b4467 to your computer and use it in GitHub Desktop.
Click to scroll menu
var navHeight = 0; //use valut for sticky menu height
$(document).on("scroll", onScroll);
$('#main-menu ul a[href*="#"]:not([href="#"]), #sidr a[href*="#"]:not([href="#"]').on('click', function (e) {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
});
$(this).addClass('active');
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top - navHeight
}, 500, 'swing', function () {
$(document).on("scroll", onScroll);
});
}
});
function onScroll(event){
var scrollPosition = $(document).scrollTop() + navHeight
$('#main-menu ul a[href*="#"]:not([href="#"])').each(function () {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var currentLink = $(this);
var refElement = $(this.hash);
if (refElement.offset().top <= scrollPosition && refElement.offset().top + refElement.outerHeight() > scrollPosition) {
$('#main-menu 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