Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 3 Scrollspy remove active state

I have a site using Bootstrap with scrollspy and a fixed header. I have it working fine, but have run into a problem with scrollspy. There are a couple sections on the page that aren't part of the main navigation. When you're in these sections, the most recent 'active' link remains. Easiest to demonstrate the issue in a fiddle:

http://jsfiddle.net/eric1086/R7S9t/1/

<body data-spy="scroll" data-target=".main-nav">
<nav class="main-nav">
  <ul class="nav">
    <li><a href="#first">First</a></li>
    <li><a href="#second">Second</a></li>
    <li><a href="#third">Third</a></li>
    <li><a href="#fourth">Fourth</a></li>
    <li><a href="#fifth">Fifth</a></li>
  </ul>
</nav>

<section class="no-spy">
    Don't spy me!
</section>
<section class="block" id="first">
    First
</section>
etc...

Basically I only want the active state to show when a targeted element from the navbar is actually showing. Any ideas? Thanks in advance!

like image 358
erh86 Avatar asked Nov 01 '22 02:11

erh86


1 Answers

The same happened to me, this is what I did.
I don't know if it's the best way to do it but it works.
Here's the code in your fiddle: http://jsfiddle.net/ZGsPm/1/

You add extra list items where your ignored sections go and add them a class ("ignore" in the example) and an id.

<body data-spy="scroll" data-target=".main-nav">
<nav class="main-nav">
  <ul class="nav">
    <li class="ignore"><a href="#no-spy-first"></a></li>
    <li><a href="#first">First</a></li>
    <li><a href="#second">Second</a></li>
    <li><a href="#third">Third</a></li>
    <li><a href="#fourth">Fourth</a></li>
    <li><a href="#fifth">Fifth</a></li>
    <li class="ignore"><a href="#no-spy-second"></a></li>
  </ul>
</nav>

Then you add the corresponding id to those sections so you can reference them from the list item.

<section class="no-spy" id="no-spy-first">
    Don't spy me!
</section>

<section class="block" id="first">
    First
</section>
...
<section class="no-spy last" id="no-spy-second">
    Don't spy me!
</section>

And finally, in Javascript (after you called the scrollspy function):

$('.ignore').css({'visibility':'hidden', 'width':'0%'});

Hope this helps!

like image 114
Javi Avatar answered Nov 11 '22 22:11

Javi