user5597624 user5597624 - 3 months ago 21
Javascript Question

Bootstrap nav menu does not scroll/affix after jQuery load

I am using jQuery to empty a div, then load a php page into the emptied div:

$("#main-container").empty();
$("#main-container").load("blog.php");


Everything works except for the Bootstrap side scrolling nav menu (included in blog.php) which affixes and scrolls as intended when merged into a single static HTML page, but not when separated and loaded in using JS as described.

HTML:

<div class="col-md-offset-10 col-md-2">
<ul class="nav nav-pills nav-stacked" id="navmenu-side" data-spy="affix" data-offset-top="400">
<h3>Categories</h3>
<li><a href="#section1">All</a></li>
<li><a href="#section2">Category 1</a></li>
<li><a href="#section3">Category 2</a></li>
<li><a href="#section3">Category 3</a></li>
</ul>
</div>


CSS:

#navmenu-side.affix {
position: fixed;
top: 200px;
width: 100%;
z-index: 10;
}
#navmenu-side.affix-bottom {
position: absolute;
width: 100%;
}


I assume this could be a result of Bootstrap events being triggered by the original page/DOM load but then not being triggered after jQuery loading. How can I make the Bootstrap side nav menu scroll/affix after it is loaded into a page using jQuery's load method?

Answer

try adding this

$("#main-container").load("blog.php", function () {
  $('#myAffix').affix('checkPosition');
});