Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Gabriel Ward
Gabriel Ward
20,222 Points

adding box-shadow on scroll

I'm trying to add a box-shadow to the bottom of my header on scroll of window. I can't see where I'm going wrong. Any help is greatly appreciated. I have the following html

<header class="main-header">    
  <nav>
    <?php
        $defaults = array(
            'container' => false,
            'theme_location' => 'gabes-menu',
            'menu_class' => 'main-nav'
        );
        wp_nav_menu( $defaults );
    ?>
</nav> 
</header>

the following css

main-header {
    position: relative;
    padding-top: 10px;
    padding-bottom: 10px;
    margin-bottom: 10px;
    height: 50px;
    background: white;
    /*background: #003399;*/

}
.box-shadow {
-webkit-box-shadow: 0 1px 3px #bbb;  /* Safari 3-4, iOS 4.0.2 - 4.2, Android 2.3+ */
    -moz-box-shadow:    0 1px 3px #bbb;  /* Firefox 3.5 - 3.6 */
    box-shadow:         0 1px 3px #bbb;  /* Opera 10.5, IE 9, Firefox 4+, Chrome 6+, iOS 5 */
}

and the following jQuery

jQuery(document).ready(function($) {
    var  tb = $('main-header');
    tbs = "box-shadow";
$(window).scroll(function() {
  if($(this).scrollTop()) {
    tb.addClass(tbs);
  } else {
    tb.removeClass(tbs);
  }
});
});

1 Answer

Codin - Codesmite
Codin - Codesmite
8,600 Points
 var $document = $(document),
   $element = $('.main-header'),
   className = 'box-shadow';

 $document.scroll(function() {
   if ($document.scrollTop() >= 50) {
     // Change 50 to the value you require
     // for the event to trigger
     $element.addClass(className);
   } else {
     $element.removeClass(className);
   }
 });

Should achieve what you are looking for.

Codepen Example here: http://codepen.io/anon/pen/BobQZK (I have set the header to fixed for demonstration so it remains in view while the page scrolls).

(Also in your css you have forgot to define "main-header" as a class with ".")

Karl Taylor
Karl Taylor
4,043 Points

You can also add a transition to the CSS by using CSS3 Transitions -

.main-header {
  transition: .5s;
  -moz-transition: .5s;
  -webkit-transition: .5s;
  position: fixed;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-bottom: 10px;
  height: 50px;
  width: 100%;
  background: white;
  /*background: #003399;*/
}

http://codepen.io/anon/pen/avMJPV