Ryan Ryan - 1 month ago 7
Javascript Question

Change Navbar Color on scroll

My navbar cannot change color on scroll, i am already using this script. please help me

<script>
$(document).ready(function(){
$(window).scroll(function() {
if ($(document).scrollTop() > 50) {
$(".navbar-fixed-top").css("background-color", "#f8f8f8");
} else {
$(".navbar-fixed-top").css("background-color", "transparent");
}
});
});
</script>


i am using bootstrap

Answer

Hope this works, you have to use scrollTop() to get vertical scrollbar position and accordingly made changes in your selected div i.e. over-here is .navbar.

$(document).ready(function(){
	$(window).on("scroll",function(){
  	var wn = $(window).scrollTop();
    if(wn > 120){
    	$(".navbar").css("background","rgba(255,0,0,1)");
    }
    else{
    	$(".navbar").css("background","rgba(1,1,1,1)");
    }
  });
});
body{
  height:1600px;
}
.navbar{
  background:rgba(1,1,1,1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<nav class="navbar navbar-fixed-top">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li> 
      <li><a href="#">Page 3</a></li> 
    </ul>
  </div>
</nav>

Comments