Search code examples
javascripthtmlcssbootstrap-4sticky

Show Navbar only when scrolling to top on mobile (Bootstrap 4)


I want to show the navbar on mobile only if the user scrolls to the top of the page.

At the moment it's stuck on the top everytime the user scrolls down or up. I'm using the code from here: https://stackoverflow.com/a/42250478/1788961 Here's the example: https://www.codeply.com/go/H7ZKuxKTKm

My JS code:

new IntersectionObserver(function(e,o){
        if (e[0].intersectionRatio > 0){
            document.documentElement.removeAttribute('class');
        } else {
            document.documentElement.setAttribute('class','stuck');
        };
    }).observe(document.querySelector('.trigger'));

Edit: to clarify what I want:

I don't want the navbar on mobile to be sticky. It should scroll away with the rest of the site. But if I'm on the bottom of the page and I scroll to the top, the navbar should appear on the top and stay there as long as I scroll to the top.


Solution

  • You would use a CSS media query only apply position:sticky on mobile (ie; <768px)...

    .sticky-top {
        position: static;
    }
    
    @media (max-width:768px) {
        .sticky-top {
            transition: all 0.25s ease-in;
            position: sticky;
        }
    
        .stuck .sticky-top {
            background-color: #222 !important;
            padding-top: 3px !important;
            padding-bottom: 3px !important;
        }
    }
    

    https://www.codeply.com/go/1b80jD3Tpg

    If you want the opposite effect (non-sticky navbar on mobile) just reverse the media query to min-width instead of max-width...

    @media (min-width:768px) {
        .sticky-top {
            transition: all 0.25s ease-in;
            position: sticky;
        }
    
        .stuck .sticky-top {
            background-color: #222 !important;
            padding-top: 3px !important;
            padding-bottom: 3px !important;
        }
    }
    

    https://www.codeply.com/go/4RtpB24k23