Bootstrap Scrollspy

The Scrollspy can be used when you need to navigate to different sections of the same page.

Thus, as you scroll, the links in the navigation bar are automatically updated.

Bootstrap Basics Scrollspy

The following code will help you understand the creation of Scrollspy.

Let’s try to understand the above code:

  • First thing we do to create a scrollspy is adding the data-spy="scroll" attribute to any element. This is generally the <body> element so that all of the page body can be added to the scrollspy
  • Next we add the data-target attribute. The value can be id or the class name of the navigation bar (.navbar). This makes sure that the navbar is connected with the scrollable area.
  • It is important that scrollable elements match the ID of the navbar’s list items (<div id="section1"> matches <a href="#section1">).
  • You can also set a data offset from the top for calculating the scroll position. This can be done using the data-offset attribute. This is essentially useful in cases when there’s inconsistency between the navbar items and the scrollable elements. The default offset is 10 pixels.
  • The data-spy="scroll" element requires relative positioning. This can be achieved using the CSS position property, with value set to “relative”.

Bootstrap Scrollspy Vertical Menu

Vertically aligned Scrollspy elements are quite common in many websites.

The code below illustrates how we can use Bootstrap’s vertical navigation pills for achieving this goal:

Bootstrap Scrollspy Options

To pass options to Scrollspy elements, you can use the data attributes or JavaScript.

By a general rule, all you need to is set the data-* attribute where * is replace by the option. Here are the options that you can use for Scrollspy

  • Offset: Takes a number value. The default value is set as 10. Used to specify the number of pixels that need to offset from top for correct positioning of the scrollable items.

Bootstrap Scrollspy Methods

Bootstrap has provides useful methods for the elements to be used for their better control.

Here’s a list of the methods for the Scrollspy element:

  • .scrollspy(“refresh”): If there are any ongoing changes on the scrollspy element, you need to refresh the page to have those chanes reflected immediately. This can be done using this method. For any addition of removal in the scrollspy element, you can have the document refreshed using this method.

Bootstrap Scrollspy Events

There is just one considerable event for the scrollspy element. Here’s the description:

  • bs.scrollspy: Event of a new item being activated by the scrollspy.