Bootstrap - Scrollspy Part 3: Dynamic Scrollspy Initialization
Scrollspy can be initialized dynamically using JavaScript, offering flexibility when working with dynamically generated content.
Examples and Explanation
JavaScript Initialization
const scrollSpy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar-example',
offset: 50
});
Explanation: This snippet initializes Scrollspy manually using Bootstrap's JavaScript API.
Dynamically Updating Scrollspy
scrollSpy.refresh();
Explanation: Use the refresh() method to update Scrollspy when the page's content changes dynamically.
Dynamic Initialization Example
<script>
document.addEventListener('DOMContentLoaded', () => {
new bootstrap.ScrollSpy(document.body, { target: '#navbar-example' });
});
</script>
Explanation: Dynamically initialize Scrollspy after the DOM content is loaded.