Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 980
user2028856 Avatar asked Dec 15 '22 04:12

user2028856


2 Answers

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");
    }
});
like image 157
Explosion Pills Avatar answered Dec 27 '22 06:12

Explosion Pills


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.

like image 32
Ennui Avatar answered Dec 27 '22 05:12

Ennui