I'm trying to make a sticky navbar on scroll with CSS and JavaScript, but it's show as a normal navbar, and it's not sticking when scrolling. How can I make it stick when it is scrolling? i added the header to the code
window.onscroll = function() {
myFunction()
};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
#navbar {
overflow: hidden;
background-color: #333;
}
/* Navbar links */
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px;
text-decoration: none;
}
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.sticky+.content {
padding-top: 60px;
}
<div class="header">
<h2>S I U</h2>
<p>T h e f u t u r e & B e y o n d</p>
</div>
<div id="navbar">
<a href="#home">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</div>
.stickyas a selector in your CSS but you don't have that class anywhere in your HTML.