user2028856
user2028856

Reputation: 3183

Change header CSS upon scrolling down

I'm trying the achieve the same header fade in/fade out effect as this website: http://www.shopstyle.com/

If you go to the website and scroll downwards, you'll see that the initial header is transparent but as you scroll down a certain number of pixels, the CSS switches to a solid background. Is this done via jquery/js or possible via CSS3?

Thank You

Upvotes: 4

Views: 16518

Answers (3)

meavo
meavo

Reputation: 1042

A combination of javascript and CSS3 should do the trick. In essence what you need to do is listen to the $(window).scroll Event and at a certain y-offset, add a class (e.g. fill) to your header:

.header { transition: all 1s; }
.header.fill { background-color:rgba(0,0,0,.25); }

Upvotes: 0

Ennui
Ennui

Reputation: 10190

Use jQuery Waypoints plugin to trigger a class change on the header at a specific scroll position/offset. There is even an extension of Waypoints specifically for this purpose (sticky elements) here. You can animate it either with CSS3 transitions/animations or jQuery UI class change animations.

From a site I made recently that has a sticky header which also animates similar to the site you linked, this is all the JS I used for that feature:

$('.header-wrap').waypoint('sticky', {
    stuckClass: 'stuck',
    offset: -1
});

offset: -1 means the change is triggered once the top of the .header-wrap element hits -1px in relation to the window (so basically once the window is scrolled AT ALL - if you put -200 it would not fire until the window had been scrolled 200px).

The class stuck change handles all of the transparency, animation, position etc.

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191749

It's not possible via CSS alone since CSS cannot select the scroll top. It's very easy to do via javascript, though.

$(window).on("scroll", function () {
    if ($(this).scrollTop() > 100) {
        $("#header").addClass("not-transparent");
    }
    else {
        $("#header").removeClass("not-transparent");
    }
});

Upvotes: 11

Related Questions