Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Scrollspy stops working after an AJAX call added elements to the page

I am using the Bootstrap scrollspy plugin (v2.0.0) which works without a problem when the page loads first.

The navigation bar as well as the content sections get updated via ajax calls (add or remove menu items). After this scrollspy doesn't highlight the newly added items anymore.

How do I tell scrollspy to refresh? Or maybe attach scrollspy manually to the following code?

  <body data-spy="scroll" data-target=".subnav" data-offset="0">
    <div id="listing">
      <div class="subnav">
        <ul class="nav nav-pills nav-stacked">
          <li><a href="#cat2">Home &amp; Garden</a></li>
          <li><a href="#cat5">Computers &amp; Networking</a></li>
        </ul>
      </div>  
      <div>
        <section id="cat2">...</section>
        <section id="cat5">...</section>
      </div>
    </div>
  </body>
like image 865
Fraxinus Avatar asked Feb 18 '12 14:02

Fraxinus


People also ask

How does Bootstrap Scrollspy work?

Scrollspy works according to the scroll position or the position at which the user is currently is seeing. Bootstrap scrollspy targets the navigation bar contents automatically on scrolling the area.

What is the purpose of using the Scrollspy plugin?

The Scrollspy plugin is used to automatically update links in a navigation list based on scroll position.

How do you make a Scrollspy in HTML?

To create a scrollspy, use the data-bs-spy=” scroll” attribute to make the required area scrollable. For example, we choose html body as the scrollable area. Give ID or class name of the navigation bar to data-bs-target attribute to connect navbar or list-group with scrollable area.


1 Answers

scrollspy('refresh') will simply do what the name says!

In my case I added the follwing code after the ajax call:

$('[data-spy="scroll"]').each(function () {
  $(this).scrollspy('refresh');
});
like image 105
Fraxinus Avatar answered Nov 15 '22 17:11

Fraxinus