December 19, 20187 yr Hey! Having a bit of trouble getting a sticky navbar to work for a website I have to build for my college course... I have copied the JavaScript from the W3Schools method assuming it would apply directly to my pre-existing navbar but it seems not...I can't seem to see where I am going wrong, any ideas? I tried using both the 'nav' and 'navbar' elements in the scripting.. Thanks in advance HTML <nav> <ul class="navbar"> <li class="navitem"><a href="">Home</a></li> <li class="navitem"><a href="">About</a></li> <li class="navitem"><a href="">Our Team</a></li> <li class="navitem"><a href="">Products</a></li> <li class="navitem"><a href="">Gallery/Portfolio</a></li> <li class="navitem"><a href="">Contact</a></li> </ul> </nav> CSS /* Navbar css*/ nav { float: left; display: block; width: 100%; left: 0; right: 0; top: 150px; background: #616A6B; height: 100px; } .navbar { list-style-type: none; max-width: 100%; text-align: center; overflow: hidden; position: static; padding-top: 25px; } .navitem { display: inline; padding-left: 10px; } .navitem a { text-decoration: none; font-size: 18px; color: white; font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif; } .navitem a:hover{ color: #CC0000; transition-duration: 0.8s; } .sticky { position: fixed; top: 0; width: 100%; } JavaScript <script> 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"); } } </script> Edited December 19, 20187 yr by jbenham10
December 20, 20187 yr Your JavaScript is looking for an id of "navbar" but that is never defined in your HTML. Adding that ID should fix your issue. As a side note I'd avoid W3Schools like the plague, it's not a good resource and is littered errors and bad advice. MDN is a much better general resource. If you are supporting more modern browsers you might want to look at using `position:sticky` - https://caniuse.com/#search=position%3Asticky - https://developer.mozilla.org/en-US/docs/Web/CSS/position then you won't need to track the scroll position against an offset in your JavaScript. If you want to do this the old way with JavaScript I'd recommend that your onScroll event is throttled because as it is you are likely to run in to performance issues, perhaps not so much in your case as you are doing the check against a cached element but in general it's considered good practice to throttle handlers that would otherwise be called in rapid succession. Edited December 20, 20187 yr by rbrtsmith
Create an account or sign in to comment