Reputation: 11
I'm trying to make a navigation where the background comes in after the user scrolls down. However, when the user is in the middle of the page, and refreshes, the background disappears and they need to scroll again for it to reappear. I'm trying to make it so whenever the user has scrolled past the header, the navigation background colour will be there no matter what.
Any help would be appreciated!
Code:
Jquery:
$(document).ready(function(){
var targetOffset = $('header').offset().top + $('header').height();
var $w = $(window).scroll(function(){
if ( $w.scrollTop() > targetOffset ) {
$("#nav").css('background-color', 'rgba(35,46,63,1)');
} else {
$('#nav').css('background-color', 'rgba(35,46,63,0)');
}
});
});
CSS:
nav {
background-color: rgba(35,46,63,0);
transition: background-color 200ms linear;
position: fixed;
left: 0;
right: 0;
padding: 25px;
z-index: 1;
box-shadow: 0px 0px 0px rgba(0,0,0,0);
}
nav > .wrapper {
overflow: hidden;
}
nav > .wrapper > li.nav-logo {
list-style: none;
font-weight: 600;
padding: 0px;
border-top: 1px solid rgba(0,0,0,0);
}
nav > .wrapper > li.nav-logo > a {
color: #DDDDDD;
text-decoration: none;
}
nav > .wrapper > li.nav-logo > a > img.left {
width: 5%;
display: inline-block;
float: left;
}
nav > .wrapper > ul.right {
list-style: none;
float: right;
}
nav > .wrapper > ul > li {
display: inline-block;
list-style: none;
font-weight: 400;
font-size: 0.9em;
padding: 15px;
border-bottom: 1px solid rgba(0,0,0,0);
border-radius: 6px;
vertical-align: middle;
transition: all 0.3s ease;
}
nav > .wrapper > ul > li > a {
color: #FFFFFF;
text-decoration: none;
transition: all .3s ease;
}
nav > .wrapper > ul > li > a:hover {
color: white;
text-decoration: none;
}
HTML:
<nav id="nav">
<div class="wrapper">
<li class="nav-logo"><a href="#"><img class="left" src="assets/images/ugn-logos/single-ugn-logo.png" alt="ugn-logo"></a></li>
<span class="nav-btn"><i class="icon-menu"></i></span>
<ul class="right">
<li><a href="index.html">Home</a></li>
<li><a href="shared-hosting.html">Shared Hosting</a></li>
<li><a href="vps.html">VPS</a></li>
<li><a href="minecraft.html">Minecraft</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
Upvotes: 0
Views: 59
Reputation: 3461
This is because $(window).scroll()
will only activate once a scroll has occurred. The same script needs to happen on $(document).ready()
. So you can create a function and call it on window resize and document ready.
$(document).ready(function(){
function changeBG() {
var targetOffset = $('header').offset().top + $('header').height();
if ( $w.scrollTop() > targetOffset ) {
$("#nav").css('background-color', 'rgba(35,46,63,1)');
} else {
$('#nav').css('background-color', 'rgba(35,46,63,0)');
}
}
changeBG();
$(window).scroll(changeBG);
});
Upvotes: 2
Reputation: 780
you can try this
$( document ).load(function(){ /* your code */ });
Upvotes: 0