Add a Class Based on Scroll Position with Javascript

YouTube video

Written By

Jonathan Jernigan

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.

    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 => {
                    if (section.getAttribute('id') === link.getAttribute('href').substring(1)) {

Signup for the most inconsistent newsletter this side of the Mississippi

Delivered on a regular-as-I-can basis, I'll share with you the tl;dr of new blog posts and videos, exciting announcements, and other valuable information from around the WordPress ecosphere. You'll never get more than one email per week from me.

"*" indicates required fields

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