Skip to content

Instantly share code, notes, and snippets.

@Trovin
Last active July 31, 2019 15:07
Show Gist options
  • Save Trovin/3eb52a58a5d70a136824a95ae7bf6474 to your computer and use it in GitHub Desktop.
Save Trovin/3eb52a58a5d70a136824a95ae7bf6474 to your computer and use it in GitHub Desktop.
JS check active section on sticky menu
//check active section
function activeSection() {
var flag = $('.page-header').hasClass('page-header_sticky');
if(flag) {
var links = $('.main-nav__link');
links.each(function(key,value) {
var newVal = $(value).attr('href');
var headerHeight = parseInt($('.page-header').height());
var currentSection = $(newVal);
var scrollToElem = currentSection.offset().top;
var scrollAfterElem = currentSection.offset().top + currentSection.height();
var winScrollTop = $(this).offset().top + headerHeight + 100;
if(winScrollTop > scrollToElem && winScrollTop < scrollAfterElem) {
links.removeClass('main-nav__link_active');
var currentLink = links[key];
$(currentLink).addClass('main-nav__link_active');
}
});
} else {
$('.main-nav__link').removeClass('main-nav__link_active');
}
}
activeSection();
//on init
activeSection();
//on scroll
$(window).on('scroll', function () {
activeSection();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment