for fixed height: http://jsfiddle.net/CriddleCraddle/Wj9dD/
dynamic height:
http://jsfiddle.net/shubhampatwa/46ovg69z/
HTML:
<nav class="navbar navbar-default" id="mainnav">
</nav>
<script>
$(document).ready(function() {
// get current top offset
var navpos = $('#mainnav').offset();
console.log(navpos.top);
$(window).bind('scroll', function() {
if ($(window).scrollTop() > navpos.top) {
// add fixed top class to make nav bar fixed
$('#mainnav').addClass('navbar-fixed-top');
}
else { // remove fixed class when window > navbar position top
$('#mainnav').removeClass('navbar-fixed-top');
}
});
});
</script>
For Mobile devices:
<script>
var newWindowWidth = $(window).width();
if (newWindowWidth < 481) {
//Place code inside it...
}
</script>