Search code examples
javascriptscroll

Add class after scrolling also need to work on refresh


I have a working script which adds a class to the body after scrolling 80px. This works but I need it to work too after having already scrolled and then refreshing the page.

So maybe replace the scroll part by position?

// fixed header
$(function() {
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll >= 80) {
            $("body").addClass('fixed');
        } else {
            $("body").removeClass("fixed");
        }
    });
});

Solution

  • you're right. you need to check the event and the initial value:

    window.addEventListener('load', function() {
        var scroll = $(window).scrollTop();
        if (scroll >= 80) {
            $("body").addClass('fixed');
        }
        //no removing needed cause refresh did it
    });