Twitter Bootstrap sticky subnav becomes fixed before it should on shorter pages
===

I've implemented an auto-floating subnav bar, taken straight from the Bootstrap [docs CSS][1] [and JS][2], in a site I'm working on. It only appears on one view, but this is a Rails view, so it is dynamically generated depending on which object is loaded.

What I've found is that, when the content that appears below the subnav bar is sufficiently long, the behavior of the subnav bar works as expected - the subnav-fixed class is added right at the moment when the subnav bar scrolls out of view.

If the page is any shorter than this however, the subnav bar will become fixed before it's actually out of view, which creates a pretty jarring jump, not to mention you can see the space where the bar used to be, which you shouldn't be able to see.

I should add that I'm using a fixed (main) navbar, with the proper body padding accounted for.

It seems that the problem is with the `$('.subnav').offset.top` value that is returned.


Could anyone who's better with jQuery / JS maybe help diagnose this, and come up with a way to make the subnav bar only become fixed when it is scrolled out of view?


The Javascript:

    var $win = $(window)
	  , $nav = $('.subnav')
	  , navTop = $('.subnav').length && $('.subnav').offset().top
	  , isFixed = 0
		, $hiddenName = $('.subnav .hide')

	processScroll()

	$nav.on('click', function () {
	  if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
	})

	$win.on('scroll', processScroll)

	function processScroll() {
	  var i, scrollTop = $win.scrollTop()
	  if (scrollTop >= navTop && !isFixed) {
	    isFixed = 1
	    $nav.addClass('subnav-fixed')
			$hiddenName.removeClass('hide')
			if (!$('.subnav li').hasClass('active')) {
				$('.subnav li:eq(1)').addClass('active')
			}
	  } else if (scrollTop <= navTop && isFixed) {
	    isFixed = 0
	    $nav.removeClass('subnav-fixed')
			$hiddenName.addClass('hide')
			$('.subnav li').removeClass('active')
	  }
	}


http://stackoverflow.com/questions/9179708/replicating-bootstraps-main-nav-and-subnav - I've seen this question, but I don't think it avoids the problem since it still uses `.offset()`


  [1]: https://github.com/twitter/bootstrap/blob/master/docs/assets/css/docs.css
  [2]: https://github.com/twitter/bootstrap/blob/master/docs/assets/js/application.js