Add a Class Based on Scroll Position with Javascript

YouTube video

Written By

Jonathan Jernigan

Found at Permaslug and APEX Web Solutions

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>

Signup for the most inconsistent newsletter this side of the Mississippi

Delivered on a regular-as-I-can basis, I summarize the goings on here on Permaslug, share announcements, and other pertinent information. I hate garbage emails as much as you and promise not to contribute anymore to it.

  • This field is for validation purposes and should be left unchanged.