Skip to content

Instantly share code, notes, and snippets.

@Catevika
Last active March 16, 2023 13:02
Show Gist options
  • Save Catevika/f20996d71679e5219b4f085c655b97e0 to your computer and use it in GitHub Desktop.
Save Catevika/f20996d71679e5219b4f085c655b97e0 to your computer and use it in GitHub Desktop.
JS: add active class to a nav item on scroll
/*=============================================
= Active class on Scroll =
=============================================*/
const sections = document.querySelectorAll('section');
const navLinks = document.querySelectorAll('nav ul li a');
window.addEventListener('scroll', function () {
let currentPos = window.scrollY;
sections.forEach(section => {
let top = section.offsetTop - 60; /* height of the nav */
let height = section.offsetHeight;
if (currentPos >= top && currentPos < top + height) {
let targetId = section.getAttribute('id');
navLinks.forEach(link => {
if (link.getAttribute('href') === `#${targetId}`) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment