Skip to content

Instantly share code, notes, and snippets.

@celsowhite
Created May 28, 2020 19:27
Show Gist options
  • Save celsowhite/43763ef556bbbf9cbbdc77d0d511029b to your computer and use it in GitHub Desktop.
Save celsowhite/43763ef556bbbf9cbbdc77d0d511029b to your computer and use it in GitHub Desktop.
Check section visibility as a user scrolls.
/*-----------------------
Offset
---
Get the offset of an element on the page relative to the document.
-----------------------*/
function offset(el) {
const rect = el.getBoundingClientRect(),
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
return { top: rect.top + scrollTop, bottom: rect.bottom + scrollTop };
}
/*-------------------------------
Check Nav Sections
---
On pages that have a sticky horizontal scrolling nav, check the nav sections as we
scroll past them to activate the appropriate menu item.
-------------------------------*/
document.addEventListener('DOMContentLoaded', event => {
const navSections = document.querySelectorAll('.nav-section');
// Check which section we are currently on and update the corresponding navigation item
function checkNavSections() {
[...navSections].forEach(section => {
// Calculate the positioning of the section
const topPosition = offset(section).top;
const bottomPosition = offset(section).bottom;
// Find the sections corresponding link
const sectionName = section.getAttribute('id');
const sectionNavLink = document.querySelector(
'.nav li[data-scroll-target="#' +
sectionName +
'"]'
);
// If scroll position is within the current section then indicate it in the navigation
const scrollBelowSectionTop = window.scrollY >= topPosition - 200;
const scrollAboveSectionBottom = window.scrollY < bottomPosition - 200;
if (scrollBelowSectionTop && scrollAboveSectionBottom) {
sectionNavLink.classList.add('active');
} else {
sectionNavLink.classList.remove('active');
}
});
}
if (navSections.length > 0) {
window.addEventListener('scroll', _debounce(checkNavSections, 20));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment