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>
Business Computing
The Business Computing BSc degree is a challenging course that provides highly relevant, hands-on experience. Through a mixture of theory and real-world practice, you’ll learn how to determine a dynamic mix of processes, which allow information delivery systems and users to carry out business effectively and efficiently. You’ll come to intuitively understand how an organisation’s information systems need to adapt to the changes and developments natural to growth and progress.