Bootstrap JS Scrollspy
JS Scrollspy
Scrollspy is used to automatically update links in a navigation list based on scroll position.
For a tutorial about Scrollspy, read our Bootstrap Scrollspy Tutorial.
Via data-* Attributes
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 top when calculating the position of scroll. This is useful when you feel
that the links inside the navbar changes the active state too soon or too early
when jumping to the scrollable elements. Default is 10 pixels.
Requires relative positioning: The element with data-spy="scroll" requires the CSS position property, with a value of "relative" to work properly.
Example
<!-- The scrollable area -->
<body data-spy="scroll"
data-target=".navbar" data-offset="50">
<!-- The navbar - The
<a> elements are used to jump to a section in the scrollable area -->
<nav class="navbar navbar-expand-sm bg-dark navbar-dark fixed-top">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#section1">Section 1</a>
</li>
....
</ul>
</nav>
<!-- Section 1
-->
<div id="section1">
<h1>Section 1</h1>
<p>Try to scroll this page and look at
the navigation bar while scrolling!</p>
</div>
...
</body>
Try it Yourself »
Via JavaScript
Enable manually with:
Scrollspy Options
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-offset="".
Name | Type | Default | Description | Try it |
---|---|---|---|---|
offset | number | 10 | Specifies the number of pixels to offset from top when calculating the position of scroll | Try it |
Scrollspy Methods
The following table lists all available scrollspy methods.
Method | Description |
---|---|
.scrollspy("refresh") | When adding and removing elements from the scrollspy, this method can be used to refresh the document |
.scrollspy("dispose") | Destroys the scrollspy |
Scrollspy Events
The following table lists all available scrollspy events.
Event | Description |
---|---|
activate.bs.scrollspy | Occurs when a new item becomes activated by the scrollspy |