Top

Bootstrap 4: Autohide navbar when scroll down

Jul 29, 2020 | 828 views

#Bootstrap

So my code was reference to: Stackoverflow

and its relative code: HERE

CSS

.navbar-tran {
    transition: top 1.0s ease;
}

.navbar-hide {
    top: -56px;
}

HTML:

<nav class="navbar navbar-tran navbar-expand-lg sticky-top navbar-dark bg-dark">
...

jQuery:


/* When the user scrolls down, hide the navbar. 
 * When the user scrolls up, show the navbar */
// document ready
(function ($) {
    
var previousScroll = 56;
    // scroll functions
    $(window).scroll(function(e) {                                                       
    
        // add/remove class to navbar when scrolling to hide/show
        var scroll = $(window).scrollTop();
        if (scroll >= previousScroll+100) {
            $('.navbar').addClass("navbar-hide");
            previousScroll = scroll;

        }else if (scroll+100 < previousScroll) {
            $('.navbar').removeClass("navbar-hide");
            previousScroll = scroll;
        }
    
    });
    
})(jQuery);

For navbar refer to here.


Leave a comment

0 comments