Skip to content

Instantly share code, notes, and snippets.

@annelyse
Created January 10, 2023 16:29
Show Gist options
  • Save annelyse/a12eb9d80a5e060d739e2b11a8314c7b to your computer and use it in GitHub Desktop.
Save annelyse/a12eb9d80a5e060d739e2b11a8314c7b to your computer and use it in GitHub Desktop.
window.addEventListener("DOMContentLoaded", function () {
navHighlighter();
});
window.addEventListener("scroll", function () {
navHighlighter();
});
const navHighlighter = () => {
// Get all sections that have an ID defined
const sections = document.querySelectorAll("[id^='section']");
const stickyOffset = document.querySelector('.fixed-header');
// Get current scroll position
let scrollY = window.pageYOffset;
// Now we loop through sections to get height, top and ID values for each
sections.forEach(current => {
const sectionHeight = current.offsetHeight;
const sectionTop = current.offsetTop - stickyOffset.offsetHeight;
const sectionId = current.getAttribute("id");
const nav = document.querySelector(".primary-menu .nav-link[href*=" + sectionId + "]");
/*
- If our current scroll position enters the space where current section on screen is, add .active class to corresponding navigation link, else remove it
- To know which link needs an active class, we use sectionId variable we are getting while looping through sections as an selector
*/
if (
scrollY > sectionTop &&
scrollY <= sectionTop + sectionHeight
) {
if (nav) {
nav.classList.add("active");
}
} else {
if (nav) {
nav.classList.remove("active");
}
}
});
}
export default navHighlighter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment