How to get dynamic data-offset values for Bootstrap 3 affix method

bigmike7801 picture bigmike7801 · Sep 9, 2013 · Viewed 44.9k times · Source

I would like to use the Affix method described in Bootstraps documentation (http://getbootstrap.com/javascript/#affix), however the navbar I would like to fix to the top of the page after it scrolls to it can have different offset values depending upon the content above it.

Here's an example of the navbar:

<div class="navbar navbar-default" data-spy="affix" data-offset-top="200">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link</a></li>
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
  </ul>
</div>

As you can see, the data-offset-top is currently set at 200. This works fine if the content above is 200px tall, but the content above is dynamic and so the height above this navbar isn't always the same. How can I make the vale for data-offset-top be dynamic?

I'm guessing I'll have to use the javascript way of doing it but I'm nit sure.

Answer

Zim picture Zim · Sep 9, 2013

You could use jQuery to get the dynamic content height above the navbar. For example:

$('#nav').affix({
      offset: {
        top: $('header').height()
      }
}); 

Working demo: http://bootply.com/69848

In some cases, offset.bottom must also be calculated to determine when to "un-affix" the element. Here's an example of affix-bottom