Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate links for Twitter Bootstrap Affix component?

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?

like image 539
Joerg Avatar asked Aug 24 '12 14:08

Joerg


1 Answers

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:

HTML

<div id="scroll-pane" data-spy="scroll" data-target="#navbar">

JS

$('#scroll-pane').scrollspy({target: '#navbar'});

Use either the HTML or the JS, but not both.


Additional Info

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.

  1. The original target must be an element which contains an element with class nav. So .nav should probably never be your target.
  2. The .nav element must contain list items.
  3. Those list items must have a <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.

like image 178
merv Avatar answered Oct 23 '22 04:10

merv