Reputation: 2610
Due to a problem described in this question about creating a responsive nav menu, I need to have two identical nav elements, one that is visible for small screens and another for large.
However I'd like scrollspy to track and apply .active
classes to both simultaneously. For simplicity's sake, lets say we have two identical navs like this one:
<div class="scrollspy navbar">
<nav class="nav">
<li><a href="#option1">Option 1</a></li>
<li><a href="#option2">Option 2</a></li>
<li><a href="#option3">Option 3</a></li>
<li><a href="#option4">Option 4</a></li>
<li><a href="#option5">Option 5</a></li>
</nav>
</div>
And then the content:
<div class="content">
<section id="option1">1</section>
<section id="option2">2</section>
<section id="option3">3</section>
<section id="option4">4</section>
<section id="option5">5</section>
</div>
And then call on scrollspy:
$(".wrapper").scrollspy({ target: ".scrollspy" });
You'll see in the fiddle that the active class gets messed up and flickers back and forth on both navs. If you remove the scrollspy
class from one of the navs, however, the other one works fine. Is this fixable?
Upvotes: 0
Views: 5756
Reputation: 39
use id instead of classes.
$(".wrapper").scrollspy({ target: "#scrollspy" });
Upvotes: 0
Reputation: 1440
If you supply an empty target, all navs work: https://stackoverflow.com/a/23937735
Just tested it myself. A surprising solution.
Upvotes: 0
Reputation: 21
This solution didn't work for me as I had 2 navs which were not identical and didn't have the same anchor links inside. (an active link in .scrollspy1 didn't necessarily had the corresponding twin in .scrollspy2)
However, a simple:
$(".wrapper").scrollspy({ target: ".scrollspy, .scrollspy2" });
was enough to fixe the flickering problem.
Upvotes: 2
Reputation: 5874
Here is the fix my friend. It is a bit mouthful, so if anyone have a more straightforward fix please go ahead. In the mean time this'll get it fixed.
$(document).ready(function () {
$(".wrapper").scrollspy({ target: ".scrollspy" });
var scollSpy2ActiveLI = "";
$('.wrapper').on('activate.bs.scrollspy', function () {
if (scollSpy2ActiveLI != "") {
scollSpy2ActiveLI.removeClass('active');
}
var activeTab = $('.scrollspy li.active a').attr('href');
scollSpy2ActiveLI = $('.scrollspy2 li a[href="' + activeTab + '"]').parent();
scollSpy2ActiveLI.addClass('active');
})
$('.wrapper').trigger('activate.bs.scrollspy');
});
Notice I am using .scrollspy2
for your second nav.
Here is the fiddle: http://jsfiddle.net/jofrysutanto/MUpz5/1/
Upvotes: 3