i want to change the color of my navbar when i scroll. When the navbar is on top the background is transparent. thank\'s to all for the attention and excuse me for my bad en
Use the Bootstrap Affix component to watch the scroll position instead of extra jQuery/JavaScript. Just define the .affix-top
and .affix
CSS for the navbar.
/* navbar style once affixed to the page */
.affix {
background-color: black;
}
@media (min-width:768px) {
.affix-top {
/* navbar style at top */
background-color:transparent;
border-color:transparent;
padding: 15px;
}
}
and set the position you want the navbar to change style (ie; 400px from the top)
<div class="navbar navbar-inverse navbar-fixed-top" data-spy="affix" data-offset-top="400">
Working Demo: http://www.codeply.com/go/xp2fY6sVHP
For Bootstrap 4, see: Animate/Shrink NavBar on scroll using Bootstrap 4
jQuery
/**
* Listen to scroll to change header opacity class
*/
function checkScroll(){
var startY = $('.navbar').height() * 2; //The point where the navbar changes in px
if($(window).scrollTop() > startY){
$('.navbar').addClass("scrolled");
}else{
$('.navbar').removeClass("scrolled");
}
}
if($('.navbar').length > 0){
$(window).on("scroll load resize", function(){
checkScroll();
});
}