How To Create A ScrollSpy Vertical Menu

Add data-spy="scroll" to the element that should be used as the scrollable area (often this is the element).

In this blog, we will learn how to create a ScrollSpy Vertical Menu to an element. Let's get started.

First, Add data-spy="scroll" to the element that should be used as the scrollable area (often this is the <body> element).

Then, add the data-target attribute with a value of the id or the class name of the navigation bar (.navbar). This is to make sure that the navbar is connected with the scrollable area.

Note that scrollable elements must match the ID of the links inside the navbar's list items (<div id="section1">matches <a href="#section1">).

The optional data-offset attribute specifies the number of pixels to offset from the top when calculating the position of scroll. This is useful when you feel that the links inside the navbar change the active state too soon or too early while jumping to the scrollable elements. The default is 10 pixels.

Important Tip

The element with data-spy="scroll" requires the CSS position property, with a value of "relative" to work properly.