How to add a CSS class on scroll

🗓️ Updated: 22.08.2022
💬Comments: 0
👁️Views: 14404

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");
    }
});

Здесь мы прописали тоже самое, если пользователь прокрутил больше 1px страницы, то header мы добавляем класс bg-red. Если меньше прокрутил – удаляем класс.

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

Was the article helpful?
👍
Yes - 24
👎
Not - 10
💬Comments:

CSS Головоломки в Telegram
Subscribe and don't miss:
Actual news
Interesting puzzles
Useful links
Our rating
🏆The best website hosting
9/10
8/10
8/10
4
8/10
8/10
7/10
7/10
Что читают?
🏆Популярные записи
How to make a burger menu – complete code and detailed explanation
Views: 54829
How to make a smooth zoom of the image on hover – effect on pure CSS
Views: 41401
Appearance of elements on scrolling
Views: 40640
How to center an image with CSS
Views: 25792
How to make a button click effect in CSS
Views: 18983
Check of knowledge
🤔How well do you know CSS?
Есть два блочных элемента, которые идут друг за другом в html. Какой будет оступ (margin) между ними, если задать им такие стили:

.top {
  height: 30px;
  background-color: blue;
  margin-bottom: 10px;
}
.bottom {
  height: 30px;
  background-color: red;
  margin-top: 20px;
}
    
10px
20px
30px
Viva Magenta
🤔Color of 2023
The Pantone Research Institute has chosen the color of the year for 2023. They became a carmine-red shade with a purple undertone, which was called Viva Magenta.
#bb2649