user3550879 user3550879 - 21 days ago 7
CSS Question

changing menu background-color when at top of screen

I have a menu which animates into view (from the top) when user scrolls up. And animates up (off screen) when user scrolls down. However, I want the background of the navigation to be black when user is at the top of the page, and white after they are a certain distance from the top.

html-snippet (working code)

...
function hasScrolled() {
if($( window ).width() > 768) {
var st = $(this).scrollTop();
if (Math.abs(lastScrollTop - st) <= delta)
return;

if (st > lastScrollTop && st > navbarHeight ) {

// Scroll Down
$('#s-nav').removeClass('nav-down').addClass('nav-up');

} else {

// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('#s-nav').removeClass('nav-up').addClass('nav-down');
}
}
} else {
$('#s-nav').removeClass('nav-up').addClass('nav-down');
}


html

<nav id="s-nav" class="row nav-down">
... nav menu ...
</nav>


css

#s-nav {
position: fixed;
z-index: 999;
background-color: #fff;
top: 0; left: 0;
width: 100%;
transition: top 0.5s ease;
}
#s-nav.nav-up { top: -75px; }

Answer

Something like this.

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 200) {
    $("#s-nav").addClass('white_bg');
  } else $("#s-nav").removeClass('white_bg');
});
body {
  background: #f1f1f1;
  height: 1000px;
}
.nav-down {
  height: 30px;
  width: 100%;
  border: 1px solid #ddd;
  position: fixed;
  background: #000;
  color: #ff0;
}
.white_bg{
  background: #000;
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav id="s-nav" class="row nav-down">
  ... nav menu ...
</nav>

Comments