[javascript] How to Bootstrap navbar static to fixed on scroll?

I would like to make static navbar to fixed navbar on scroll, when it reaches top of the page.

Is there a way to get it using bootstrap 3 css or javascript?

This question is related to javascript jquery html css twitter-bootstrap-3

The answer is


The question is a bit older, it's solved by CSS and latest bootstrap natively.

If you add the class sticky-top to your navbar it will behave just like the javascript/jquery in the best current answer but without any javascript.
Browser support is quite decent but not perfect.


If I'm not wrong, what you're trying to achieve is called Sticky navbar.

With a few lines of jQuery and the scroll event is pretty easy to achieve:

$(document).ready(function() {

    var menu = $('.menu');
    var content = $('.content');
    var origOffsetY = menu.offset().top;

    function scroll() {
        if ($(window).scrollTop() >= origOffsetY) {
            menu.addClass('sticky');
            content.addClass('menu-padding');
        } else {
            menu.removeClass('sticky');
            content.removeClass('menu-padding');
        }
    }

    $(document).scroll();

});

I've done a quick working sample for you, hope it helps: http://jsfiddle.net/yeco/4EcFf/

To make it work with Bootstrap you only need to add or remove "navbar-fixed-top" instead of the "sticky" class in the jsfiddle .


/** * Scroll management */ $(document).ready(function () {

// Define the menu we are working with
var menu = $('.navbar.navbar-default.navbar-inverse');

// Get the menus current offset
var origOffsetY = menu.offset().top;

/**
 * scroll
 * Perform our menu mod
 */
function scroll() {

    // Check the menus offset. 
    if ($(window).scrollTop() >= origOffsetY) {

        //If it is indeed beyond the offset, affix it to the top.
        $(menu).addClass('navbar-fixed-top');

    } else {

        // Otherwise, un affix it.
        $(menu).removeClass('navbar-fixed-top');

    }
}

// Anytime the document is scrolled act on it
document.onscroll = scroll;

});


_x000D_
_x000D_
/**_x000D_
 * Scroll management_x000D_
 */_x000D_
$(document).ready(function () {_x000D_
_x000D_
    // Define the menu we are working with_x000D_
    var menu = $('.navbar.navbar-default.navbar-inverse');_x000D_
_x000D_
    // Get the menus current offset_x000D_
    var origOffsetY = menu.offset().top;_x000D_
_x000D_
    /**_x000D_
     * scroll_x000D_
     * Perform our menu mod_x000D_
     */_x000D_
    function scroll() {_x000D_
_x000D_
        // Check the menus offset. _x000D_
        if ($(window).scrollTop() >= origOffsetY) {_x000D_
_x000D_
            //If it is indeed beyond the offset, affix it to the top._x000D_
            $(menu).addClass('navbar-fixed-top');_x000D_
_x000D_
        } else {_x000D_
_x000D_
            // Otherwise, un affix it._x000D_
            $(menu).removeClass('navbar-fixed-top');_x000D_
_x000D_
        }_x000D_
    }_x000D_
_x000D_
    // Anytime the document is scrolled act on it_x000D_
    document.onscroll = scroll;_x000D_
_x000D_
});
_x000D_
.navbar-wrapper{_x000D_
    background:url('http://www.wallpaperup.com/uploads/wallpapers/2012/10/21/20181/cad2441dd3252cf53f12154412286ba0.jpg');_x000D_
    height: 100vh;_x000D_
  padding-top: 50px;_x000D_
}_x000D_
_x000D_
h1{_x000D_
  font-size: 50px;_x000D_
  font-weight: 700;_x000D_
}_x000D_
_x000D_
#login-dp{_x000D_
    min-width: 250px;_x000D_
    padding: 14px 14px 0;_x000D_
    overflow:hidden;_x000D_
    background-color:rgba(255,255,255,.8);_x000D_
}_x000D_
#login-dp .help-block{_x000D_
    font-size:12px    _x000D_
}_x000D_
#login-dp .bottom{_x000D_
    background-color:rgba(255,255,255,.8);_x000D_
    border-top:1px solid #ddd;_x000D_
    clear:both;_x000D_
    padding:14px;_x000D_
}_x000D_
#login-dp .social-buttons{_x000D_
    margin:12px 0    _x000D_
}_x000D_
#login-dp .social-buttons a{_x000D_
    width: 49%;_x000D_
}_x000D_
#login-dp .form-group {_x000D_
    margin-bottom: 10px;_x000D_
}_x000D_
.btn-fb{_x000D_
    color: #fff;_x000D_
    background-color:#3b5998;_x000D_
}_x000D_
.btn-fb:hover{_x000D_
    color: #fff;_x000D_
    background-color:#496ebc _x000D_
}_x000D_
.btn-tw{_x000D_
    color: #fff;_x000D_
    background-color:#55acee;_x000D_
}_x000D_
.btn-tw:hover{_x000D_
    color: #fff;_x000D_
    background-color:#59b5fa;_x000D_
}_x000D_
@media(max-width:768px){_x000D_
    #login-dp{_x000D_
        background-color: inherit;_x000D_
        color: #fff;_x000D_
    }_x000D_
    #login-dp .bottom{_x000D_
        background-color: inherit;_x000D_
        border-top:0 none;_x000D_
    }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<body>_x000D_
<div class="navbar-wrapper">  _x000D_
  <div class="container">_x000D_
    <nav class="navbar navbar-default navbar-inverse" role="navigation">_x000D_
  _x000D_
    <!-- Brand and toggle get grouped for better mobile display -->_x000D_
    <div class="navbar-header">_x000D_
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
        <span class="sr-only">Toggle navigation</span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
        <span class="icon-bar"></span>_x000D_
      </button>_x000D_
      <a class="navbar-brand" href="#">Login dropdown</a>_x000D_
    </div>_x000D_
_x000D_
    <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
        <ul class="nav navbar-nav">_x000D_
          <li class="active"><a href="#">Link</a></li>_x000D_
          <li><a href="#">Link</a></li>_x000D_
          <li class="dropdown">_x000D_
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a>_x000D_
            <ul class="dropdown-menu" role="menu">_x000D_
              <li><a href="#">Action</a></li>_x000D_
              <li><a href="#">Another action</a></li>_x000D_
              <li><a href="#">Something else here</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">Separated link</a></li>_x000D_
              <li class="divider"></li>_x000D_
              <li><a href="#">One more separated link</a></li>_x000D_
            </ul>_x000D_
          </li>_x000D_
        </ul>_x000D_
      _x000D_
      </div><!-- /.navbar-collapse -->_x000D_
    </nav>_x000D_
  </div><!-- container -->_x000D_
</div><!-- /.navbar-wrapper -->_x000D_
  _x000D_
 <section>_x000D_
   <div class="container">_x000D_
     <div class="row">_x000D_
       <h1>Content</h1>_x000D_
       <p>_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi congue luctus placerat. Sed nisl sem, pellentesque at risus eget, consequat bibendum velit. Sed interdum accumsan luctus. Duis rhoncus suscipit hendrerit. Vestibulum ut lobortis diam. Donec magna est, euismod non ligula in, congue aliquet diam. Sed pellentesque erat nibh, et blandit quam auctor eget. Integer fringilla turpis ac sagittis mattis. In in metus posuere, tincidunt orci non, lobortis ipsum. Praesent porttitor orci a ligula facilisis porta. Nullam tincidunt feugiat dignissim._x000D_
       </p>_x000D_
       <p>_x000D_
         Pellentesque cursus suscipit massa ut molestie. Duis malesuada consequat venenatis. Vestibulum accumsan lorem sit amet vehicula tristique. Donec nec mauris quis mi imperdiet vestibulum. Praesent tempor velit at posuere posuere. Mauris tellus diam, dictum sed molestie eu, lobortis nec diam. Mauris molestie nulla vulputate, lobortis urna eget, gravida erat. Phasellus in ullamcorper lacus, eget ullamcorper odio._x000D_
       </p>_x000D_
       <p>_x000D_
         Quisque gravida nulla eros. Duis sit amet rhoncus felis. Etiam in malesuada nisl. Proin sit amet elit sit amet erat dapibus pretium. Duis a dignissim lacus, vitae mollis nunc. Donec ut tempor magna. Maecenas eget felis eget ipsum porttitor dapibus vitae vitae magna. Cras et felis eros. Nam dolor odio, bibendum ut ex eu, facilisis suscipit ipsum. Aliquam sit amet nunc volutpat, aliquet nunc ut, tempor augue. Pellentesque semper vestibulum lacinia. Nam lacinia erat interdum purus consequat elementum. Phasellus volutpat sed libero id molestie. Quisque nec iaculis nisl, vitae accumsan justo. Suspendisse sollicitudin metus in libero cursus tempor in eget enim._x000D_
       </p>_x000D_
       <p>_x000D_
         Suspendisse nibh lacus, consequat et tincidunt eget, interdum mollis velit. Etiam lobortis ac tellus et pretium. Nunc a tincidunt nulla. Cras vel nulla in neque accumsan fermentum. Etiam ac erat leo. Vestibulum aliquam dignissim lectus, tincidunt consequat augue malesuada at. Pellentesque semper viverra elit quis vestibulum. Aliquam rutrum justo dignissim ligula fringilla, ac viverra metus efficitur._x000D_
       </p>_x000D_
       <p>_x000D_
         Mauris quis nisi convallis, rhoncus odio non, sodales urna. Donec ac ante at nisi pulvinar eleifend. Duis vel suscipit est. Nullam quis aliquet eros. Maecenas tincidunt augue condimentum nisi pharetra, in molestie libero condimentum. In hac habitasse platea dictumst. Morbi quis elit id nunc faucibus egestas. Sed non vehicula ligula, quis viverra urna. Nunc nec eleifend elit. Sed aliquam nibh non turpis congue, a condimentum mauris dictum. Vivamus laoreet nulla vel elit consequat, non convallis nibh dapibus. Mauris maximus nibh maximus, sollicitudin odio nec, semper nunc. Nunc consequat convallis lobortis. Aliquam pulvinar porttitor lorem. Donec luctus, libero a interdum posuere, est tellus tincidunt risus, a fermentum lacus odio at metus. Donec maximus ante massa, imperdiet consequat magna lobortis sed._x000D_
       </p>_x000D_
     </div>_x000D_
   </div>_x000D_
 </section>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_


hey all everyone is over thinking this all you need to do is wrap the nav in a like below:

csscode:

#navwrap {  
    height: 100px;   (change dependant on hight of nav)
    width: 100%;
    margin: 0;
    padding-top: 5px;
}

HTML:

<div id="navwrap">
    nav code inside
</div>

If you handle the code like this:

<div class="scroll"> 
<div class="menu">home | services | contact</div>
</div>

And css:

.scroll {
  margin-bottom:50px;
}
.menu {
  position:absolute;
  background:#428bca;
  color:#fff;
  line-height:30px;
  letter-spacing:1px;
  width:100%;
  height:50px;
}
.menu-padding {
  // no  style here anymore 
}

Then the annoying scroll is gone.

The compleet code and fiddle is not originally made by me, I got it from an earlier answer in this topic. The change in the code is made by me

Fabian #Web-Stars

jsfiddle


Set on nav

style="position:fixed; width:100%;"

Use the affix component included with Bootstrap. Start with a 'navbar-static-top' and this will change it to fixed when the height of your header (content above the navbar) is reached...

$('#nav').affix({
      offset: {
        top: $('header').height()
      }
}); 

http://bootply.com/107973


set max-height as you need:

.navbar-fixed-top 
.navbar-collapse, 
.navbar-fixed-bottom 
.navbar-collapse {
    max-height: 700px;
}

I am note sure, what you are expecting. Have a look at this fiddle, this might help you.

http://jsfiddle.net/JK52L/8/

You HTML should have the class navbar-fixed-top or navbar-fixed-bottom.

HTML

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
  <!-- Brand and toggle get grouped for better mobile display -->
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- Collect the nav links, forms, and other content for toggling -->
  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Link 1</a></li>
      <li><a href="#">Link 2</a></li>
    </ul>
  </div><!-- /.navbar-collapse -->
</nav>

JS

$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        console.log(scrollTop);
        $('.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
    } else {
        $('.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
    }
});

Or you can change position of specific div using class name

$(document).scroll(function(e){
    var scrollTop = $(document).scrollTop();
    if(scrollTop > 0){
        //console.log(scrollTop);
        $('.header').css("position","fixed");
    } else {
         $('.header').css("position","relative");
    }
});

Here is my implementation using the Affix Bootstrap plugin http://getbootstrap.com/javascript/#affix

It includes some extra affix problems solved (see below).

HTML:

<nav class="navbar navbar-inverse navbar-fixed-top" id="top_navbar">
  <div class="container-fluid">
... (typical Bootstrap top navbar)
  </div>
</div>

...
...
...

<div id="parent-navbar-main" >
  <div id="navbar-main">
... (here is your nav panel to get sticky on scroll)
  </div>
</div>

Javascript:

function set_sticky_panel()  {

  var affixElement = $('#navbar-main');

  var navbarElementHeight = $('#top_navbar').height();

// http://stackoverflow.com/questions/18683303/bootstrap-3-0-affix-with-list-changes-width
  var width = affixElement.parent().width();
  affixElement.width(width);

// http://stackoverflow.com/questions/3410765/get-full-height-of-element
  var affixElementHeight = $('#navbar-main').outerHeight(true);

// https://finiteheap.com/webdev/2014/12/26/bootstrap-affix-flickering.html  
  affixElement.parent().height(affixElementHeight);

// http://stackoverflow.com/questions/23797241/resetting-changing-the-offset-of-bootstrap-affix
  $(window).off('.affix')
  affixElement.removeData('bs.affix').removeClass('affix affix-top affix-bottom')


  affixElement.affix({
    offset: {
    // Distance of between element and top page
      top: function () {
      // how much scrolling is done until sticking the panel
        return (this.top = affixElement.offset().top - parseInt(navbarElementHeight,10))
      }
    }
  });

  // The replacement for the css-file.
  affixElement.on('affix.bs.affix', function (){
  // the absolute position where the sticked panel is to be placed when the fixing event fires (e.g. the panel reached the top of the page).
    affixElement.css('top', navbarElementHeight + 'px');
    affixElement.css('z-index', 10);
  });

}

$(document).on('ready', set_sticky_panel);

$(window).resize(set_sticky_panel);

CSS:

No css is required.

If to compare with the standart implementation my code additionaly solves these problems:

  1. The width of the sticky panel does not break at the fixing event anymore.
  2. The need in the CSS-file usage is eliminated.
  3. Reformatting the sticky panel size on the window change size event (responsiveness) is done now.
  4. No more affix flittering / jumping at the fixing event.

I faced the same problem but the solution that worked for me was:

HTML:

<header class="container-fluid">
    ...
</header>
<nav class="row">
    <div class="navbar navbar-inverse navbar-static-top">
        ...
    </div>
</nav>

JavaScript:

document.onscroll = function() {
    if( $(window).scrollTop() > $('header').height() ) {
        $('nav > div.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
    }
    else {
        $('nav > div.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
    }
};

Where header was the banner tag above my navigation bar


Here's a solution using Bootstrap's affix plugin:

HTML:

<header class="container-fluid">
    ...
</header>
<nav class="navbar navbar-default navbar-static-top" role="navigation">
    ...
</nav>

Javascript:

$('nav').affix({
      offset: {
        top: $('header').height()
      }
});

Set padding-top to your body equal to that of your nav's height so that the content overlayed by the fixed navbar is visible.

$('nav').on('affix.bs.affix', function (){
     $('body').css('margin-top', $('nav').height());
});

$('nav').on('affix-top.bs.affix', function (){
     $('body').css('margin-top', 0);
});

To get the nav to stick on top while scrolling add this bit of CSS.

CSS:

.affix
{
    top: 0;
}

If you are using Bootstrap 4, which is the latest version as writing this answer, the assingments have changed a bit. Here is an example of a navbar fixed on top:

<nav class="navbar fixed-top navbar-light bg-light">
    <a class="navbar-brand" href="#"><h1>Navbar</h1></a>
</nav>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to twitter-bootstrap-3

bootstrap 4 responsive utilities visible / hidden xs sm lg not working How to change the bootstrap primary color? What is the '.well' equivalent class in Bootstrap 4 How to use Bootstrap in an Angular project? Bootstrap get div to align in the center Jquery to open Bootstrap v3 modal of remote url How to increase Bootstrap Modal Width? Bootstrap datetimepicker is not a function How can I increase the size of a bootstrap button? Bootstrap : TypeError: $(...).modal is not a function