This code will automatically add and remove a class based on scroll position using vanilla JavaScript. In my case, I used it to add an active class to an a link as the user scrolled down the sections on my site.
You can change the selectors it uses by adjusting the ‘section’ and ‘a’ parameters to suit your use case.
<script>
const sections = document.querySelectorAll('section');
const links = document.querySelectorAll('a');
window.addEventListener('scroll', () => {
let scrollPosition = window.scrollY + 80;
sections.forEach(section => {
if (scrollPosition >= section.offsetTop) {
links.forEach(link => {
link.classList.remove('active');
if (section.getAttribute('id') === link.getAttribute('href').substring(1)) {
link.classList.add('active');
}
});
}
});
});
</script>