![]() |
VOOZH | about |
Bootstrap5 Scrollspy Methods are used to control the Scrollspy element with the help of Javascript and perform operations like disposing, getting or creating the Scrollspy instance, refreshing the element, etc along with finding out useful data about the widget within Javascript.
It is used in automatically update navigation or list group links based on scroll position. This is particularly useful for highlighting sections in a long page, providing a better user experience.
Bootstrap 5 Scrollspy Methods:
The Scrollspy component includes several methods to control its behavior with JavaScript. These methods allow you to create, refresh, or destroy Scrollspy instances and obtain useful data about the widget.
The Scrollspy component comes with the following methods:
// to dispose
scrollSpyInstance.dispose();
// For getting the instance
bootstrap.ScrollSpy.getInstance(element);
// For creating and getting the instance
bootstrap.ScrollSpy.getOrCreateInstance(element);
// to refresh
scrollSpyInstance.refresh();
Example 1: In this example, we have a scrollspy element and we use the getOrCreateInstance method to create an instance of the element and then obtain that instance and its properties on the console. Here, we haven't used the dispose method to dispose the instances.
Output:
Example 2: In this example, we use the getOrCreateInstance method to get the instance and then dispose the instance using the dispose method.
Output: From the output, the dispose method does not affect the scrollspy element but removes all the stored data of that element, and hence in output we have all the values of the scrollspy object set to null.
Bootstrap 5's Scrollspy component and its methods provide powerful tools for enhancing user navigation experience. By understanding and utilizing these methods, developers can efficiently manage and manipulate Scrollspy instances.
Reference: https://getbootstrap.com/docs/5.2/components/scrollspy/#methods