Reputation: 3
I'm creating a page where the navigation bar should only appear after scrolling a few thousand pixels. But when I refresh the browser, the navigation bar appears first and disappears as soon as I start scrolling. After that everything works as intended.
How can I make the bar hidden when the page is refreshed?
Here the JS code I have used:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){$(window).scroll(function(){
if( $(this).scrollTop() > 4000){
$('#navigation').fadeIn( "slow", "linear" )
} else {
$('#navigation').fadeOut( "slow", "linear" )
}
})
})
</script>
Here the CSS code I have used:
nav ul {
position:fixed;
list-style: none;
width: 1100px;
height: 40px;
margin: 30px 222px auto;
padding: 20px 20px 20px 20px;
background-color: #798c39;
text-align: center;
}
Upvotes: 0
Views: 2277
Reputation: 993
Maybe try another way. Instead of doing everything with jquery I recommend using pure javascript and css. This method is more efficient and works better.
const nav = document.querySelector('#navigation');
function showNav(){
nav.classList.add('show');
}
function hidewNav(){
nav.classList.remove('show');
}
var currPos = window.scrollY;
document.addEventListener('scroll', () => {
if (window.scrollY < currPos) {
//scroll up
hidewNav();
} else {
//scroll down
showNav();
}
currPos = window.scrollY;
});
body {
margin: 0;
height: 2000px;
margin-top: 100px;
}
nav {
position: fixed;
list-style: none;
width: 100%;
height: 70px;
top: 0;
margin: 0;
background-color: #798c39;
text-align: center;
transform: translateY(-100px);
transition: 0.3s;
}
.show {
transform: translateY(0);
}
<html>
<head>
</head>
<body>
<header>
<nav id="navigation">
<ul>
</ul>
</nav>
</header>
<main>
</main>
</body>
</html>
Upvotes: 1
Reputation: 36512
It depends on whether the navbar's space is to be reserved for it or not on load.
I suspect it is given the JS you have shown, in which case you need to ensure it has opacity: 0 on load.
The only alteration to your code would be in the stylesheet add:
nav {
opacity: 0;
}
This is assuming that the fadeIn/fadeOut keyframes just alter opacity. It they alter some dimension as well, for example, that would also need catering for. Perhaps you could show us those keyframes so we can check?
Upvotes: 0