I am using the Twitter Bootstrap Affix JS component. My UL list is affixing properly when I scroll the page down. Also - when I click on the individual list items (much like Twitter does on its docs page), it scrolls down to my anchor ID in my document, but the LI element does not receive the Twitter 'active' class. Nor does it get the 'active' class when I scroll my document.
I would expect the appropriate link to be active when I have scrolled to the particular part in the document (much like scroll-spy works), but I can't seem to get this to work.
Is there something special I need to set up so that Bootstrap will add the 'active' class when appropriate?
Yes, you need to also use the ScrollSpy plugin. You can activate it through markup or through JS. Letting #scroll-pane
be the element that triggers scroll events and #navbar
be the element containing the ul.nav
, the following should get it working:
<div id="scroll-pane" data-spy="scroll" data-target="#navbar">
$('#scroll-pane').scrollspy({target: '#navbar'});
Use either the HTML or the JS, but not both.
When the ScrollSpy plugin is passed a target, like scrollspy({target: '#navbar'})
, this is used to construct a selector of the form
target + ' .nav li > a'
which, in this example would give
'#navbar .nav li > a'
It is important to understand the stipulations that this selector creates.
target
must be an element which contains an element with class nav
. So .nav
should probably never be your target..nav
element must contain list items.<a>
as a direct child.The <a>
elements selected by this are then filtered out by those whose data-target
or href
begin with a '#'. These href
's are in turn used to select the elements contained in the element to which the ScrollSpy plugin is attached. Offsets of those selected are stored, and when a scroll occurs, a comparison of the current scroll offset is made with the stored values, updating the corresponding <a>
element with the class active
.
Hopefully, this summary can aid in better understanding what one might be tripping over when attempting to implement the plugin, without having to dig into the code in further detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With