Andres SK
Andres SK

Reputation: 10974

Displaying a shadow on the fixed #topbar only if the user scrolled down

I have a #top bar in my website. It is always visible at the top and travels with the user as the user scrolls. It works fine. Now I want to display a shadow on the #top bar only if the scrollbar position is > 0. If the user goes to the top, it must dissapear.

#top {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 80px;
    z-index: 9999;
}
#top.shadow {
    -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
    -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
}

Solution (based on Godwin's answer)

$(window).scroll(function(){
    if($(window).scrollTop() > 0) {
        $('#top').addClass('shadow');
    } else {
        $('#top').removeClass('shadow');
    }
});

...but I believe that is not the best way to go -- seems to have a low performance on old computers/browsers. Any ideas?

Upvotes: 0

Views: 4150

Answers (3)

ScottS
ScottS

Reputation: 72261

A solution that uses just css, assuming the shadow is a small one: http://jsfiddle.net/cJuFz/111/.

body { /* just for illustration */
    height: 2000px; 
    background-color: white;
}
body:before,
#top,
body:after {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 80px;
    z-index: 9999;
    background-color: yellow;
}
body:before{
    content: '';
    display: block;
    z-index: 9997;
    -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
    -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.3);
}
body:after {
    content: '';
    display: block;
    position: absolute; /* this needs to scroll */
    background-color: white; /* match background of body */
    top: 80px;
    height: 3px; /* covers height of :before shadow */ 
    z-index: 9998; /* overlap :before, moves on scroll */
}

Upvotes: -1

adeneo
adeneo

Reputation: 318272

Just for fun, here's another way to do it:

var elm = $("#top");

$(document).scroll(function() {
    elm.toggleClass('shadow', elm.offset().top > 0);
});

Upvotes: 1

Godwin
Godwin

Reputation: 9907

Here's a solution using jQuery:

$(document).ready(function(){
  $(window).scroll(function(){
    var y = $(window).scrollTop();
    if( y > 0 ){
      $("#top-shadow").show();
    } else {
      $("#top-shadow").hide();
    }
  });
})​

Upvotes: 6

Related Questions