I\'m trying to ditch jQuery from my upcoming projects. I found a way to create a sticky nav on scroll with pure Vanilla JS, and wanted the links on my navigation to change t
You can get all sections and links using document.querySelectorAll()
. On scroll iterate the list of section from last to first, until you find one that matches. Then remove the .active
class from all links, and add it to the link at the active index
.
Note: You should use throttling to prevent the calling of changeLinkState
multiple times in a second. Another option is to use the Intersection Observer API.
const links = document.querySelectorAll('.links');
const sections = document.querySelectorAll('section');
function changeLinkState() {
let index = sections.length;
while(--index && window.scrollY + 50 < sections[index].offsetTop) {}
links.forEach((link) => link.classList.remove('active'));
links[index].classList.add('active');
}
changeLinkState();
window.addEventListener('scroll', changeLinkState);
nav {
position: fixed;
top: 0;
right: 0;
width: 10em;
}
section {
height: 100vh;
margin: 1em 0;
background: gold;
}
.active {
background: silver;
}
Home
About Us
Services
Clients
Contact