Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a sticky navbar using twitter bootstrap?

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.

like image 765
espanapin Avatar asked Aug 24 '12 17:08

espanapin


2 Answers

is this what you are looking for?

<div class="navbar navbar-fixed-top">
like image 100
Yilmaz Guleryuz Avatar answered Nov 18 '22 22:11

Yilmaz Guleryuz


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.

like image 26
steve Avatar answered Nov 18 '22 22:11

steve