VOOZH about

URL: https://www.geeksforgeeks.org/bootstrap/bootstrap-5-scrollspy-refresh-method/

⇱ Bootstrap 5 Scrollspy refresh() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bootstrap 5 Scrollspy refresh() Method

Last Updated : 23 Jul, 2025

Bootstrap 5 Scrollspy provides a refresh() method that is invoked while including or discarding the elements in the DOM tree, i.e., it can be manually called to recalculate the active link based on the current scroll position. This method can be used to update the active link whenever the page content changes dynamically.

The ScrollSpy constructor is used to create a new scroll spy instance on the document.body element with the #navbar as the target. The refresh() method is called on the scrollspy instance to refresh the scrollspy.

Syntax:

let scrollspy = new bootstrap.ScrollSpy(document.body, {
target: '#navbar'
})
scrollspy.refresh()

Approach 1: Here, the HTML code contains a navigation menu with four items. Each item is a hyperlink with a unique ID that corresponds to a section of the page that the user can scroll to. The 'data-bs-spy', 'data-bs-target', and 'data-bs-offset' attributes are added to the container div to activate Scrollspy functionality. The JavaScript code initializes the Scrollspy by creating a new instance of the bootstrap.ScrollSpy class. An event listener is added to the "Toggle Section" button. When the button is clicked, this will show or hide one of the sections on the page.

After the display property is toggled, the scrollSpy.refresh() method is called to update the scroll spy. This method recalculates the positions of the target elements and updates the scrollspy accordingly.

Example 1: The following code example illustrates the basic usage of the refresh() Method for updating scrollspy after rendering/hiding sections.

Output: 

Approach 2: Here, the code creates a fixed-top navbar with four navigation links that correspond to four sections on the page. The data-bs-spy attribute on the HTML div element that wraps these sections enables the Scrollspy component. The data-bs-target attribute specifies the ID of the navbar that will be used for navigation, and the data-bs-offset attribute specifies the number of pixels to offset from the top when calculating the position of scrollable elements.

The JavaScript code initializes the Scrollspy component using bootstrap.ScrollSpy constructor. Then, the code adds an event listener to the "Change Section Heights" button that randomly changes the height of each section using JavaScript's Math.random() method. After each change, the code calls the Scrollspy's refresh() method to update the scrollspy component with the new section heights.

Example 2: This code example demonstrates the usage of the refresh() Method for updating Scrollspy after dynamically changing section heights.

Output:

Reference: https://getbootstrap.com/docs/5.2/components/scrollspy/#methods

Comment
Article Tags:

Explore