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.
I was having a lot of trouble with this earlier, and for some reason I couldn't get any of the solutions other people had suggested to work. I'm relatively new to Bootstrap and JQuery, so I was probably doing something wonky I wasn't catching. Regardless, I found a solution that works really well, although it doesn't strictly speaking use the affix functionality as Bootstrap intends. I kept my
#thisElement.affix {top: desiredFixedPosition;}
CSS intact, but got rid of thedata-spy
anddata-offset-top
attributes from #thisElement's HTML tag. I then hard-coded this in JQuery:As far as I've tested, this works regardless of how much you resize the page or scroll, and if you get creative with how you call it in the
$(document).ready()
function you could even have the menu remain in the right position during height animations. As stated, this isn't technically a fully "Bootstrap approved" solution, but it integrates well enough into a Bootstrap site that it should work for some :)