Replicating Bootstraps main nav and subnav

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');
});

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


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/