Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure js add and remove (toggle) class after scrolling x amount?

Tags:

javascript

I don't want to use jQuery for this.

It's really simple, I just want to add a class after scrolling past a certain amount of pixels (lets say 10px) and remove it if we ever go back to the top 10 pixels.

My best attempt was:

var scrollpos = window.pageYOffset;
var header = document.getElementById("header");

function add_class_on_scroll() {
    header.classList.add("fade-in");
}

function remove_class_on_scroll() {
    header.classList.remove("fade-in");
}

window.addEventListener('scroll', function(){
    if(scrollpos > 10){
        add_class_on_scroll();
    }
    else {
        remove_class_on_scroll();
    }
    console.log(scrollpos);
});

But console shows a number that continues to grow regardless of scrolling up or down. And the class fade-in never gets added, though console shows we past 10.

like image 416
John_911 Avatar asked Dec 14 '22 11:12

John_911


1 Answers

You forgot to change the offset value in the scroll handler.

//use window.scrollY
var scrollpos = window.scrollY;
var header = document.getElementById("header");

function add_class_on_scroll() {
    header.classList.add("fade-in");
}

function remove_class_on_scroll() {
    header.classList.remove("fade-in");
}

window.addEventListener('scroll', function(){ 
    //Here you forgot to update the value
    scrollpos = window.scrollY;

    if(scrollpos > 10){
        add_class_on_scroll();
    }
    else {
        remove_class_on_scroll();
    }
    console.log(scrollpos);
});

Now you code works properly

Explanation

There is no documentation for that, like you asked for. This is just an issue in the logic workflow.

When you say that scrollpos = window.scrollY your page is at an top-offset of 0, so your variable stores that value. When the page scrolls, your scroll listener will fires. When yout listener checks for the scrollpos value, the value is still 0, of course. But if, at every scroll handler, you update the scrollpos value, now you can have a dynamic value.

Another option is you to create a getter, like

var scrollpos = function(){return window.scrollY};

This way you can dynamically check what that method will return for you at every offset.

if(scrollpos() > 10)

See? Hope that helped. (:

like image 195
Filipe Merker Avatar answered Dec 17 '22 01:12

Filipe Merker