Creating a sticky navbar using twitter bootstrap?

16,953

Solution 1

is this what you are looking for?

<div class="navbar navbar-fixed-top">

Solution 2

You do not have any CSS for navbar-fixed-top. Also, you need to handle when you scroll back up.

See demo http://jsfiddle.net/yTqSc/39/

JavaScript

$(document).scroll(function(){
var elem = $('.subnav');
if (!elem.attr('data-top')) {
    if (elem.hasClass('navbar-fixed-top'))
        return;
     var offset = elem.offset()
    elem.attr('data-top', offset.top);
}
if (elem.attr('data-top') <= $(this).scrollTop() )
    elem.addClass('navbar-fixed-top');
else
    elem.removeClass('navbar-fixed-top');
});

CSS

.subnav {
    background:#FFF;
}
.navbar-fixed-top {
    position:fixed;
}

Or use Waypoints jquery plugin to handle sticky elements.

Share:
16,953
Admin
Author by

Admin

Updated on July 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to introduce a navbar that, when no longer in view, then adopts fixed header positioning. I started by using this thread: Replicating Bootstraps main nav and subnav.

    Since then, I have arrived at: http://jsfiddle.net/yTqSc/2/.

    The problem:

    The anchor links will overshoot their target (therein hiding the destination heading) whenever the navbar is in its original position, but not once it is fixed. I can fix the overshoot (I referred to http://nicolasgallagher.com/jump-links-and-viewport-positioning/demo/), but then I end up with an excessive gap using the links when the navbar is fixed.

    Can anyone advise how to obtain consistent results regardless of whether the navbar is fixed or not?

    Thanks.

  • Admin
    Admin over 11 years
    I am not sure how this answers the question. I am already adding this class dynamically using javascript, and it seems to be at the root of the problem. The inconsistent behavior occurs as a result of adding this class after navigating to an anchor link.