Add a Class Based on Scroll Position with Javascript

WordPress

December 7, 2022

No video URL found

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>

Join the Inside Link Community

Get access to all courses, weekly office hours, live build sessions, and an active community of WordPress professionals.

Learn More →