Search code examples
jquerytwitter-bootstrapnavbarscrollspy

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 .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?


Solution

  • 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/