How to add a CSS class on scroll
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.