dougmacklin dougmacklin - 1 year ago 106
jQuery Question

Bootstrap Scrollspy with Multiple Navbars

Here is a fiddle.

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

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>

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>

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
class from one of the navs, however, the other one works fine. Is this fixable?

Answer Source

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('', function () {
        if (scollSpy2ActiveLI != "") {
        var activeTab = $('.scrollspy a').attr('href');
        scollSpy2ActiveLI = $('.scrollspy2 li a[href="' + activeTab + '"]').parent();


Notice I am using .scrollspy2 for your second nav.

Here is the fiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download