Skip to content
Advertisement

Add/remove class with jquery based on vertical scroll?

So basically I’d like to remove the class from ‘header’ after the user scrolls down a little and add another class to change it’s look.

Trying to figure out the simplest way of doing this but I can’t make it work.

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();    
    if (scroll <= 500) {
        $(".clearheader").removeClass("clearHeader").addClass("darkHeader");
    }
}

CSS

.clearHeader{
    height: 200px; 
    background-color: rgba(107,107,107,0.66);
    position: fixed;
    top:200;
    width: 100%;   
}    

.darkHeader { height: 100px; }

.wrapper {
    height:2000px;
}

HTML

<header class="clearHeader">    </header>
<div class="wrapper">     </div>

I’m sure I’m doing something very elementary wrong.

Advertisement

Answer

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

     //>=, not <=
    if (scroll >= 500) {
        //clearHeader, not clearheader - caps H
        $(".clearHeader").addClass("darkHeader");
    }
}); //missing );

Fiddle

Also, by removing the clearHeader class, you’re removing the position:fixed; from the element as well as the ability of re-selecting it through the $(".clearHeader") selector. I’d suggest not removing that class and adding a new CSS class on top of it for styling purposes.

And if you want to “reset” the class addition when the users scrolls back up:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
        $(".clearHeader").addClass("darkHeader");
    } else {
        $(".clearHeader").removeClass("darkHeader");
    }
});

Fiddle

edit: Here’s version caching the header selector – better performance as it won’t query the DOM every time you scroll and you can safely remove/add any class to the header element without losing the reference:

$(function() {
    //caches a jQuery object containing the header element
    var header = $(".clearHeader");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 500) {
            header.removeClass('clearHeader').addClass("darkHeader");
        } else {
            header.removeClass("darkHeader").addClass('clearHeader');
        }
    });
});

Fiddle

Advertisement