I am trying to implement this bit of code to enable a sticky nav bar on my website: https://www.w3schools.com/howto/howto_js_navbar_sticky.asp
I keep getting the following error: "index.html:44 Uncaught TypeError: Cannot read property 'remove' of undefined"
Here is the snippet:
<body class="is-preload">
<div class="topnav">
<a class="active" href="#header">Home</a>
<a href="#first">Book an Appointment</a>
<a href="#second">Contact</a>
<a href="#third">About</a>
</div>
<script>// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the navbar
var navbar = document.getElementsByClassName("topnav");
// Get the offset position of the navbar
var sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}</script>
I cant figure out for the life of me whats wrong. Its the exact bit of code from the W3C site and it wrks fine there.