Juliver Galleto
Juliver Galleto

Reputation: 9047

Add bottom box shadow to the menu on scrollup and scrolldown

I have a menu with this CSS properties:

#header {
  width: 100%;
  position: fixed;
  z-index: 9000;
  overflow: auto;
}

So based on the CSS properties above, this element (#header) will obviously remain on top regardless of the scrolling. What I'm trying to achieve is on scroll up and scroll down, a bottom box shadow should be added into that element (#header) and should be removed once it reaches the default location of that element (#header) which is obviously the top-most place of the page.

I'm open to any suggestion and recommendation.

Upvotes: 15

Views: 20867

Answers (2)

Turnip
Turnip

Reputation: 36702

$(window).scroll(function() {     
    var scroll = $(window).scrollTop();
    if (scroll > 0) {
        $("#header").addClass("active");
    }
    else {
        $("#header").removeClass("active");
    }
});
body {
    height: 2000px;
    margin: 0;
}

body > #header{position:fixed;}

#header {
    width: 100%;
    position: fixed;
    z-index:9000;
    overflow: auto;
    background: #e6e6e6;
    text-align: center;
    padding: 10px 0;
    transition: all 0.5s linear;
}

#header.active {
     box-shadow: 0 0 10px rgba(0,0,0,0.4);   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="header">HEADER</div>

JSFiddle version

Whenever the page is scrolled we save the current distance from the top of the document in a variable (scroll).

If the current position is greater than 0 we add the class active to #header.

If the current position is equal to 0 we remove the class.

Upvotes: 36

Andrew Clody
Andrew Clody

Reputation: 1181

Create a class called shadow to add to your header div on window.scroll.

http://jsfiddle.net/43aZ4/

var top = $('#header').offset().top;
  $(window).scroll(function (event) {
    var y = $(this).scrollTop(); 
    if (y >= 60) {  $('#header').addClass('shadow'); }
    else { $('#header').removeClass('shadow'); }
  });

.shadow {
    -webkit-box-shadow: 0px 10px 5px rgba(50, 50, 50, 0.75);
    -moz-box-shadow:    0px 10px 5px rgba(50, 50, 50, 0.75);
    box-shadow:         0px 10px 5px rgba(50, 50, 50, 0.75);
}

Upvotes: 3

Related Questions