Question

I have a submenu that gets loaded via ajax. I'm trying to use Bootstraps scrollspy to highlight the submenu based on where the user is on the current page. However it doesn't work with my sub-menu. I believe its because its loaded via ajax. How can I get the sub-menu to highlight?

subnav.html

<div class="span3 affix">
    <div class="well sidebar-nav">
        <ul class="nav nav-list">
            <li class="nav-header">Document</li>
        <li><a href="#a">A</a></li>
        <li><a href="#b">B</a></li>
        </ul>
     </div><!--/.well -->
</div><!--/span-->

Mainpage.html

<body>
    <div id="sub-nav"></div>

    <div id="a" style="margin-bottom:200px;"></div>

    <div id="b" style="margin-bottom:200px;"></div>

</body>

<script>
jQuery(function(){
    $('#sub-nav').load('apps_subnav.html');
    $('body').scrollspy();
});
</script>
Was it helpful?

Solution

You should wait on jQuery's AJAX request to complete [and eventually for the data to be appended] before trying to bind the scrollspy. Make use of the $().load() callback.

jQuery(function(){
  $('#sub-nav').load('subnav.html', function(){
    $('body').scrollspy();
  });
});

OTHER TIPS

Seems like your $('#body').scrollspy() is misplaced, as the document isn't ready when you call $('#body').

UPDATE: Since you have your script block below the <body>, ignore the statement above.

Also, if you want to target <body> element, use $('body') without the # (as # targets elements with ids).

Try this:

jQuery(function(){
    $('#sub-nav').load('subnav.html');
    $('body').scrollspy();       
    // Or did you intend to target an element with id 'body'?
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top