Bootstrap Scrollspy Plugin

The Bootstrap Scrollspy plugin is for auto updating nav which allows you to target based (sections of the page) on scroll position. The .active class change while scrolling the page under the navbar. Sub items of the dropdown will be highlighted as well.

If you want to implement functionality of this plugin individually, simple include the scrollspy.js file along the other JS files. Else as we have discussed in the tutorial of Bootstrap Plugin Overview, you can include bootstrap.js or the minified bootstrap.min.js.


Via data attribute of JavaScript you can scrollspy behavior to your topbar navigation below is the details of both methods.

Via data attributes

You can easily add scrollspy behavior to your topbar navigation. Add data-spy=”scroll” to the element you want to spy on (typically the body). Then add attribute data-target with the ID or class of the parent element of any Bootstrap .nav component. Yu must have element or tag in the body area of the page that should have same IDs with the links that you are spring on.

Via JavaScript

After adding position: relative; in your CSS, you can call the scrollspy with JavaScript instead of data attributes.

Navbar links must have resolvable id targets. For example, a home must correspond to something in the DOM like 


Example of Bootstrap Scrollspy Plugin

Use this code to check to use of scrollspy plugin via data attributes:


Options can be passed via data attributes or JavaScript. Append the option name to data-, as in data- for data attributes. Following table lists the options:

Option Name Type/Default Value Data attribute name Description
offset number
Default: 10
data-offset Pixels to offset from top when calculating position of scroll.



While using the scrollspy method via the JavaScript, you will need to call the .refresh method to update the DOM.  This method is helpful if you make changes in any DOM element like if you removed or added some elements. Follow this syntax to use this method.


See the use of .scrollspy(‘refresh’) method


Following table lists the events to work with scrollspy. This event may be used to hook into the function.

Event name:

This event fires whenever a new item becomes activated by the scrollspy.

Event code:


See the following example to use of event:

Leave a Reply

Your email address will not be published. Required fields are marked *