AI Bootstrap Builder Logo
AI Bootstrap Builder Questions & Answers

How can I hide the navbar when scrolling down and show on scroll up using utilities only?

Asked on Jun 06, 2025

1 Answer

To hide the navbar when scrolling down and show it on scroll up using Bootstrap utilities, you can use the `position-sticky` utility along with some custom JavaScript to toggle visibility.
<!-- BEGIN COPY / PASTE -->
        <nav id="navbar" class="navbar navbar-expand-lg navbar-light bg-light position-sticky top-0">
            <div class="container-fluid">
                <a class="navbar-brand" href="#">Brand</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link active" aria-current="page" href="#">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Features</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Pricing</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <script>
            let lastScrollTop = 0;
            window.addEventListener('scroll', function() {
                let navbar = document.getElementById('navbar');
                let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
                if (scrollTop > lastScrollTop) {
                    navbar.style.top = '-70px'; // Adjust based on navbar height
                } else {
                    navbar.style.top = '0';
                }
                lastScrollTop = scrollTop;
            });
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • The `position-sticky` utility keeps the navbar fixed at the top when scrolling.
  • JavaScript is used to detect scroll direction and hide/show the navbar.
  • Adjust the `navbar.style.top` value based on your navbar's height.
  • Ensure the navbar is initially visible by setting `top` to `0`.
✅ Answered with Bootstrap 5 best practices.
← Back to All Questions