javascriptnavbarsticky

Javascript classlist.add code only partially working


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!

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.


Solution

  • That is, when I scroll down the NAV sticks to the top of the page but when I scroll back up it remains "stuck"

    This a little bit unclear to me… So, if you scroll up, navbar stays in place where you change direction, or nav stay (and doesn’t disappear) in initial position?

    Try this approach (simply set in proper way display, when we mean about initial showing)

    And, like @Ry- mentioned, avoid document.write(), if you don’t want problems

    https://developer.mozilla.org/en-US/docs/Web/API/Document/write

    https://developer.chrome.com/docs/lighthouse/best-practices/no-document-write

        <nav id="MainNav" class="navbar">
            <h1> sticky Navbar</h1>
        </nav>
        <div style="padding:15px 0; height:1500px;">
            <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem
    </p>
        </div>
    
    //—-
    
    .navbar {
        width: 100%;
        background: #333;
        color: white;
        padding: 10px 0;
        text-align: center;
        position: -webkit-sticky;
        position: sticky;
        top: 0;
        z-index: 1000;
        display: none; /* hide (if you need by default) */
    }
    
    .navbar.visible {
        display: block;
    }
    
    //—-
    
    document.addEventListener("DOMContentLoaded", function() {
        const navbar = document.getElementById('MainNav');
    
        window.addEventListener('scroll', function() {
            if (window.scrollY > 0) {
                navbar.classList.add("visible");
            } else {
                navbar.classList.remove("visible");
            }
        });
    });
    

    https://codepen.io/Lucas_Mas/pen/pomLwLK