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.

JavaScript

CSS

JavaScript

HTML

JavaScript

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

Advertisement

Answer

JavaScript

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:

JavaScript

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:

JavaScript

Fiddle

Advertisement