Reputation: 11
I am attempting to mimic the navbar that is seen on this site, but am having some trouble with the JQuery. I am using an if statement for the scroll formatting and then include a hover method in the bottom of the if statement.
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("nav").css("background-color","white");
$("nav").css("height","75px");
$(".navbar-default .navbar-brand").css("color","black");
$(".navbar-default .navbar-nav > li > a").css("color","black");
}
else {
$("nav").css('background-color','rgba(0, 0, 0, 0)');
$(".navbar-default .navbar-brand").css("color","white");
$(".navbar-default .navbar-nav > li > a").css("color","white");
$("nav").css("height","125px");
$("nav").hover(function(){
$(this).css("background-color", "white");
}, function(){
$(this).css("background-color", "rgba(0, 0, 0, 0)");
});
}
});
});
The issue with the current code I have is that the hover method is changing the navbar after I scroll to be transparent when I would like it to not change and stay white.
Upvotes: 0
Views: 59
Reputation: 33880
You use too much JavaScript. You should let CSS style your elements. Instead of using multiple times .css
, you should simply add a class to the nav
then style based on that.
The .hover
part can also be done in CSS. Rule of thumbs, you should never ever attach event handler inside an other event handler; there is always a better way.
In the end, you should have something like this :
Disclaimer, I did not style like you did, nor used your HTML, so you should adapt this code to your needs.
$(function() {
var $window = $(window).scroll(function() {
var scroll = $window.scrollTop();
$("nav").toggleClass("sticked", scroll >= 100);
});
});
body{
height : 300vh;
}
nav{
position : fixed;
top : 0;
left : 0;
width : 100%;
height : 125px;
background : transparent;
}
nav .text{
color : black;
}
nav:hover{
background: red;
}
nav:hover .text{
color : white;
}
nav.sticked{
background : red;
height : 75px;
}
nav.sticked .text{
color : white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
<span class="text">text here</span>
</nav>
Upvotes: 1