Search code examples
htmlcssnavbar

Add horizontal line on scroll on boostrap navbar


I need to add horizontal line to the boostrap navbar when I scroll the page. Simply said, when page loads and navbar is on the top, line should not be visible, but when user scroll down the page, I need to have visible bottom line of the navbar.

I know it's possible to achieve this via various libaries such as waypoints or so, but I'm looking for most simple and clean way how to do it, ideally just with jquery or boostrap.

Thank you :)


Solution

  • <style>
        .scrolled {border-bottom:1px solid #000;}    
    </style>
    
    $(document).scroll(function(){
         $('#navbar').toggleClass('scrolled', $(this).scrollTop() > 1);
    });
    

    assuming your navbar has an ID of "navbar".

    This will add a class of 'scrolled' to the navbar anytime you scroll more than 1 pixel down, which you can then style in CSS. It will also disappear when you return to the top of the page.