I'm trying to make some code to make a sticky navbar, such that the position is fixed when I scroll down, however, it doesn't work. I wonder if the CSS is the problem, because most of the HTML and javascript would not really affect it. I have tried it on some of my other websites, and they work, but it doesn't seem to work on this one.
<div id="main-nav">
<nav>
<h2 id="logo" class="main-nav">Captain Max from ERA</h2>
<br>
<ul class="main-nav">
<li> <a href="#">Listings</a></li>
<li> <a href="#">Get in touch</a></li>
<li> <a href="#">Projects</a></li>
</ul>
</nav>
</div>
The script for this is here, I'm not sure if anything is wrong with this though.
<script>
var navbar = document.getElementById("main-nav");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
</script>
The CSS is here, it seems like I made a property that altered how the sticky keyboard works.
.sticky {
position: fixed;
top: 0;
width: 100%
}
.sticky + .content {
padding-top: 60px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-family: 'Raleway', sans-serif;
font-size: 20px;
font-weight: 300;
text-rendering: optimizeLegibility;
}
nav {
background-color: #7b8195;
color: #e9e6df;
overflow: hidden;
}
#logo {
font-family: 'Raleway', sans-serif;
font-size: 250%;
border-top: 10px;
padding-right: 150px;
padding-left: 10px;
padding-top: 10px;
}
nav li {
display:inline-block;
margin-left: 40px;
}
.main-nav {
float: left;
list-style: none;
margin-right: 60px;
border-bottom: 10px;
padding-bottom: 10px;
}
.main-nav li a {
float: right;
color: #e9e6df;
text-decoration: none;
font-size: 90%;
}
.main-nav li a:link,
.main-nav li a:visited{
padding-bottom: 8px;
color: #e9e6df;
text-decoration: none;
font-size: 90%;
border-bottom: 2px solid transparent;
transition: border-bottom 0.2s;
}
.main-nav li a:hover,
.main-nav li a:active{
border-bottom: 2px solid #e9e6df;
}
The link to the website is here
What I can see here in your website is you havn't closed the script
properly. You have missed one closed }
brases.
<script>
var navbar = document.getElementById("main-nav");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
</script>