Javascript – Using bootstrap scrollspy for a div with collapse, to an affixed sidebar

javascriptjquerytwitter-bootstrap

I have this code as the layout of the page. The span9 div cotains sections that should apply the scrollspy. Each section is a set of collapsible divs that contains the actual content. The span3 div is the affixed sidebar and must highlight the correct item using the scrollspy.

<div class="span3 module-sidebar">
    <ul id="sidebar" data-spy="affix"  data-offset="250" data-offset-bottom="0" class="nav nav-list bs-docs-sidenav affix">
        <li>
            <a href="#module1"><i class="icon-chevron-right"></i>Module1 Name</a>
        </li>
    </ul>
</div>

<div class="span9" data-spy="scroll" data-target="#sidebar">
    <section id="module1">
        <div class="page-header">
            <h1>Module1 Name</h1>
        </div>

        <div class="bs-docs-example">
            <div class="accordion" id="accordion2">
                <div class="accordion-group">
                    <div class="accordion-heading">
                        <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#function1">Function1 Name</a>
                    </div>
                    <div id="function1" class="accordion-body collapse in">
                        <div class="accordion-inner">
                        <h3>Topic1 Name</h3>
                        <p>Topic1 Desc</p>                              
                            <h4>SubTopic1 Name</h4>
                            <p>SubTopic1 Desc</p>                                   
                                <h4><img src="../assets/img/manuals/module1/function1/step1.png"/></h4>
                                <p>Step1 Desc</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

The problem is that when i collapse the div to show the content, the scrollspy won't recognize the newly occupied space by that collapsible div. and thus highlights the next items in the sidebar when I scroll through the content of that collapsible div.

What i want is for the scrollspy to 'see' the space when the collapsible div is expanded. Any help would really be appreciated. Click here for the fiddle.

Best Answer

You should call .scrollspy('refresh') :

$(document).ready(function () {

    $('.accordion').on('shown hidden', function () {
        $('body').scrollspy('refresh');
    });

});