Reputation: 59
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
Upvotes: 0
Views: 11142
Reputation: 655
I am just curious on why arent you using affix that already comes with bootstrap? Here is the link : http://www.w3schools.com/Bootstrap/bootstrap_affix.asp
in your case change add this line for your nav tag
<nav class="navbar navbar-fixed-top"data-spy="affix" data-offset-top="(scroll value)" >
and css
.affix.navbar{
background-color: color-you-prefer;
}
Upvotes: 2
Reputation: 8795
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>
Upvotes: 6
Reputation: 475
Use the css class
for color:
.anycolor {
background-color: #f8f8f8";
}
and do that with this code :
if ($(window).scrollTop() > 50){
$('.navigation').addClass( "anycolor");
}
else {
$('.navigation').removeClass("anycolor");
}
Upvotes: 0