ScrollSpy component

Scrollspy is a component that automatically updates Bootstrap navigation or list group components based on scroll position to indicate which link is currently active in the viewport. Scrollspy has a few requirements to function properly:

  • It must be used on a Bootstrap nav component or list group.
  • Scrollspy requires position: relative; on the element you’re spying on, usually the <body> or <div class="content-inner">.
  • When spying on elements other than the <body>, be sure to have a height set and overflow-y: scroll; applied.
  • Anchors (<a>) are required and must point to an element with that id.
Usage via Data Attributes

To easily add scrollspy behavior to your topbar navigation, add data-spy="scroll" to the element you want to spy on (most typically this would be the <body>). Then add the data-target attribute with the ID or class of the parent element of any Bootstrap .nav component.

Add CSS styles:

                            
												.content-wrapper {
													position: relative;
												}
											
										

And add markup:

                            
												<div class="content-inner" data-spy="scroll" data-target=".sidebar-component-right">
													[...]
													<div class="sidebar sidebar-light sidebar-component sidebar-component-right sidebar-sticky ...">
														<div class="sidebar-content">
															[...]
														</div>
													</div>
													[...]
												</div>
											
										
Usage via JavaScript

After adding position: relative; in your CSS, call the scrollspy via JavaScript:

                            
												// Initialize
												$('.content-inner').scrollspy({ target: '.sidebar-component-right' });
											
										
Scrollspy Methods

Scrollspy supports 2 methods: refresh - when using scrollspy in conjunction with adding or removing of elements from the DOM, you'll need to call the refresh method; dispose - destroys an element’s scrollspy.

                            
												// Refresh Scrollspy
												$('[data-spy="scroll"]').each(function () {
													var $spy = $(this).scrollspy('refresh')
												});

												// Destroy Scrollspy
												$('[data-spy="scroll"]').scrollspy('dispose');
											
										
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
offset number 10 Pixels to offset from top when calculating position of scroll.
Scrollspy Events
Event Type Description
activate.bs.scrollspy This event fires whenever a new item becomes activated by the scrollspy.

Example code:

                            
												// When Scrollspy is activated
												$('#myScrollspy').on('activate.bs.scrollspy', function () {
													// do something…
												});