AI Bootstrap Builder Logo
AI Bootstrap Builder Questions & Answers

How do I implement ScrollSpy on a page loaded with AJAX content?

Asked on Jun 04, 2025

1 Answer

To implement ScrollSpy with AJAX-loaded content in Bootstrap 5, you need to initialize ScrollSpy after the content is dynamically added to the page. This ensures that the ScrollSpy functionality recognizes the new elements.
<!-- BEGIN COPY / PASTE -->
        <!-- HTML Structure -->
        <nav id="navbar-example" class="navbar navbar-light bg-light">
            <a class="navbar-brand" href="#">Navbar</a>
            <ul class="nav nav-pills">
                <li class="nav-item">
                    <a class="nav-link" href="#section1">Section 1</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section2">Section 2</a>
                </li>
            </ul>
        </nav>
        
        <div data-bs-spy="scroll" data-bs-target="#navbar-example" data-bs-offset="0" class="scrollspy-example" tabindex="0">
            <!-- AJAX content will be loaded here -->
        </div>

        <!-- JavaScript to initialize ScrollSpy after AJAX load -->
        <script>
            // Function to load content via AJAX
            function loadContent() {
                // Simulate AJAX content loading
                document.querySelector('.scrollspy-example').innerHTML = `
                    <h4 id="section1">Section 1</h4>
                    <p>Content for section 1...</p>
                    <h4 id="section2">Section 2</h4>
                    <p>Content for section 2...</p>
                `;
                
                // Re-initialize ScrollSpy
                var scrollSpy = new bootstrap.ScrollSpy(document.body, {
                    target: '#navbar-example'
                });
            }

            // Call the function to load content
            loadContent();
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • Ensure that the `data-bs-spy="scroll"` attribute is set on the container where the AJAX content will be loaded.
  • After loading content via AJAX, re-initialize ScrollSpy using the `bootstrap.ScrollSpy` constructor.
  • The `target` option in ScrollSpy should match the ID of the navigation element.
  • You can simulate AJAX loading by calling the `loadContent` function, which updates the content and re-initializes ScrollSpy.
✅ Answered with Bootstrap 5 best practices.
← Back to All Questions