I’ve been struggling to get Navbar menu to “stick” when I scroll down the page. I’m inserting the html “nav code” using JS and I’ve included the JS “stick” code in the inserted file but it only sticks and won’t unstick. That is, when I scroll down the NAV sticks to the top of the page but when I scroll back up it remains “stuck”. So I moved the “stick” code to follow the “insert” code in the HTML and have the same issue. This, after using the innerHTML method of inserting the “nav code” and getting a “Navbar variable is null” error despite multiple manipulations of the code. The test file (with “native” HTML – not inserted HTML – and innerHTML JS works fine) so it’s something to do with inserting the HTML (I think). Here’s my current code:
<div id="fixed" class="fixed-header"> <script src="header.js"></script> <script src="header-scroll.js"></script> </div>
The “header.js” is simple – it uses document.write() to insert the HTML (and the HTML does contain the id=”MainNav” attribute!). Here’s the header-scroll JS:
` window.onscroll = function() { navStick() };
window.navStick = function() {
var navbar = document.getElementById('MainNav');
var sticky = navbar.offsetTop;
if (window.scrollY >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}`
Any help would be greatly appreciated as its driving me mad!
Sorry – explained this in the first text box! The code works fine in the HTML without the nav code “native” (not inserted) but falls over, no matter what I’ve tried, when the nav code is inserted.