I have a navigation witch changes background color etc. when scrolling past 10px. But if i stay past 10px and refresh the page it goes back to having a transparent background, until i start scrolling the page.
How do i make the function work when refreshing the page past 10px?
Code:
window.onload = scrollNavi;
function scrollNavi() {
$(window).scroll(function () {
var scroll = $(window).scrollTop();
if (scroll > 10) {
$(".navbar").css({ "background-color": "white", "box-shadow": "rgba(99, 99, 99, 0.2) 0px 2px 8px 0px" });
$(".nav-item").css("color", "#707070");
$(".logo").attr("src", "/images/logo/ccc-logo-new.png");
$(".navi-icon").css("color", "#707070");
}
else {
$(".navbar").css({ "background": "none", "box-shadow": "none" });
$(".nav-item").css("color", "white");
$(".logo").attr("src", "/images/logo/ccc-logo-hvid.png");
$(".navi-icon").css("color", "white");
}
});
};
As you se above i have tried activate it with a window.onload but that doesn't seem to help.
Nav:
<nav class="navbar fixed-top navbar-expand-xl navbar-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<img class="logo" src="/images/logo/ccc-logo-hvid.png" alt="" height="65">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-
target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-
expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</div>
</nav>
CodePudding user response:
When calling scrollNavi()
, all you are doing is registering an event handler for the scroll javascript event.
What you should do is store the scroll event handler in a function and call it on page load.
function scrollNavi() {
var scroll = $(window).scrollTop();
if (scroll > 10) {
$(".navbar").css({ "background-color": "white", "box-shadow": "rgba(99, 99, 99, 0.2) 0px 2px 8px 0px" });
$(".nav-item").css("color", "#707070");
$(".logo").attr("src", "/images/logo/ccc-logo-new.png");
$(".navi-icon").css("color", "#707070");
}
else {
$(".navbar").css({ "background": "none", "box-shadow": "none" });
$(".nav-item").css("color", "white");
$(".logo").attr("src", "/images/logo/ccc-logo-hvid.png");
$(".navi-icon").css("color", "white");
}
};
window.onload = scrollNavi;
$(window).scroll(scrollNavi);