AndrewLeonardi AndrewLeonardi - 7 months ago 28
Javascript Question

How to toggle a sticky header?

The code below makes a sticky header which shows up once you've scrolled down 100px. How do I make the sticky header turn off once I get to a lower part of the page? Lets say 800px?

Thanks!

$(window).scroll(function() {
if ($(this).scrollTop() > 100){
$('header').addClass("sticky");
}

else{
$('header').removeClass("sticky");
}
})

Answer

Do you mean like this?

$(window).scroll(function() {
    if ($(this).scrollTop() > 100 && $(this).scrollTop() < 800) {  
        $('header').addClass("sticky");
    } else{
        $('header').removeClass("sticky");
    }
})