The affix plugin allows a <div>
to become affixed to a location on the page. You can also toggle it's pinning on and off using this plugin. A common example of this are social icons. They will start in a location, but as the page hits a certain mark, the <div>
will be locked in place and will stop scrolling with the rest of the page.
Usage
You can use the affix plugin via data attributes or manually with your own JavaScript as discussed below.
Enable Affix via Data Attributes
You can easily add affix behavior to any element — just add data-spy="affix"
to the element you want to spy on. Then add the data-offset-top|bottom
attribute to calculate the position of the scroll.
Example
<ul class="nav nav-tabs nav-stacked" data-spy="affix" data-offset-top="195">
<li class="active"><a href="#one">Section One</a></li>
<li><a href="#two">Section Two</a></li>
<li><a href="#three">Section Three</a></li>
</ul>
Enable Affix via JavaScript
You may also enable the affix plugin manually using the JavaScript — just call the affix()
method with the id
or class
selector of the required element in your JavaScript code.
Example
<script type="text/javascript">
$(document).ready(function(){
$("#myNav").affix({
offset: {
top: $(".header").outerHeight(true)
}
});
});
</script>