I need to quickly knock up the functionality of the twitter bootstraps main navigation and sub navigation e.g. http://twitter.github.com/bootstrap/scaffolding.html (when you
Great Answer from @Oleg,
For people like me who want to reproduce the responsive behaviour of the .subnav
Here is the css code (without colors, borders and effects)
body { padding-top: 90px; }
@media (max-width: 980px) {
body {
padding-top: 0;
}
}
.subnav {
width: 100%;
}
@media (max-width: 768px) {
.subnav {
position: static;
top: auto;
z-index: auto;
width: auto;
height: auto;
}
.subnav .nav > li {
float: none;
}
}
@media (min-width: 980px) {
.subnav-fixed {
position: fixed;
top: 40px;
left: 0;
right: 0;
z-index: 1020;
}
.subnav-fixed .nav {
width: 938px;
margin: 0 auto;
}
}
@media (min-width: 1210px) {
.subnav-fixed .nav {
width: 1168px;
}
}
If you want to clone the style of the menu (including colors, borders and effects)
http://jsfiddle.net/baptme/ydY6W/
As of 2012-12-04 the accepted answer is no longer the best choise, since the desired functionality has been included into Bootstrap. Please see Affix JavaScript component which is part of Bootstrap JS
Here is another code
$(function(){
var
$win = $(window),
$filter = $('.navbar'),
$filterSpacer = $('<div />', {
"class": "filter-drop-spacer",
"height": $filter.outerHeight()
});
$win.scroll(function(){
if(!$filter.hasClass('navbar-fixed-top')){
if($win.scrollTop() > $filter.offset().top){
$filter.before($filterSpacer);
$filter.addClass("navbar-fixed-top");
}
}else if ($filter.hasClass('navbar-fixed-top')){
if($win.scrollTop() < $filterSpacer.offset().top){
$filter.removeClass("navbar-fixed-top");
$filterSpacer.remove();
}
}
});
});
Here is my code to implement this feature:
$(document).scroll(function(){
// If has not activated (has no attribute "data-top"
if (!$('.subnav').attr('data-top')) {
// If already fixed, then do nothing
if ($('.subnav').hasClass('subnav-fixed')) return;
// Remember top position
var offset = $('.subnav').offset()
$('.subnav').attr('data-top', offset.top);
}
if ($('.subnav').attr('data-top') - $('.subnav').outerHeight() <= $(this).scrollTop())
$('.subnav').addClass('subnav-fixed');
else
$('.subnav').removeClass('subnav-fixed');
});
The two answers above work great, but I just thought I'd let people know that I've made this into a module (without the jQuery dependency) available at ForbesLindesay/booting-sub-nav. It can be used standalone with a script tag or via https://github.com/component/component/