How to add a CSS class on scroll

Владимир Самойлов
Дата: 17.07.2023
Comments: 0
Views: 23895
Content:

Let’s solve this problem: we need to add a class to a given element (for example, header) on scroll.

Let’s go. We can solve this problem with JavaScript. I will prescribe two solutions – with pure JS and using JQUERY library.

Adding a class to an element on page scroll (Pure JavaScript):

//Record how many pixels are scrolled vertically
let scrollpos = window.scrollY

const header = document.querySelector("header")

//How many pixels you need to scroll to add a class. You can change the value
const scrollChange = 1

//The function that will add the class
const add_class_on_scroll = () => header.classList.add("bg-red")

//Tracking a "scroll" event
window.addEventListener('scroll', function() { 
  scrollpos = window.scrollY;

//If we scrolled more than we specified in the scrollChange variable, the add class function is executed
  if (scrollpos >= scrollChange) { add_class_on_scroll() }
})

Let’s improve this code and remove the class if you scroll less than 1px:

let scrollpos = window.scrollY

const header = document.querySelector("header")
const scrollChange = 1

const add_class_on_scroll = () => header.classList.add("bg-red")
const remove_class_on_scroll = () => header.classList.remove("bg-red")

window.addEventListener('scroll', function() { 
  scrollpos = window.scrollY;

  if (scrollpos >= scrollChange) { add_class_on_scroll() }
  else { remove_class_on_scroll() }
  
})

Here we have added a new function remove_class_on_scroll, which removes a certain class from the chosen element. This function will be executed if the user has not scrolled 1px from the beginning of the page.

Now let’s write the same thing in jquery:

var header = $(".header");
var scrollChange = 1;
$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= scrollChange) {
        header.addClass('bg-red');
    } else {
        header.removeClass("bg-red");
    }
});

Here we wrote the same thing, if the user scrolled more than 1px of the page, we add bg-red class to the header. If the user scrolled less, we remove the class.

This is how you can easily add or remove a class to any element when you scroll the page.

Was the article helpful?
👍
Yes - 31
👎
Not - 16
Comments: