Twitter Bootstrap ScrollSpy tutorial
Description
In this document, you will see how to use Twitter Bootstrap ScrollSpy Plugin to automatically update nav targets based on scroll position.
What is required
You must include Jquery, Twitter Bootstrap CSS and one JavaScript file - bootstrap-scrollspy.js, which is located under 'js' folder of Twitter Bootstrap's main folder. If you are using a dropdown menu, then you need to include bootstrap-dropdown.js in the HTML file.
Jquery is available under docs >assets > js of your Twitter Bootstrap's main folder as jquery.js; or you may point to https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js to load Jquery.
This what you will end up building by the end of this tutorial:
Using Twitter Bootstrap ScrollSpy in your website
Explanation
So, you need to add 'data-spy="scroll" ' in the target division.
Note that we have added the style of .scrollspy-example additionally in the head section of the example file. This is because .scrollspy-example is not available in bootstrap.css, instead, it is available in docs.css.
The value of the 'data-offset' attribute, which is a number, determines, the number of pixels to offset from the top when calculating the position of scroll.
Call .scrollspy()
You may call .scrollspy() via JavaScript to make ScrollSpy work. This may be done in this fashion :
Where #navbar is the id of the associated navigation.
Methods
You may use scrollspy along with creating and removing elements from DOM. But if you do so, you have to call the refresh method . The following code shows how you may do that:
Options
If you are calling scrollspy by javaScript, you may use 'offset' method to determine the number of pixels to offset from the top when calculating the position of scroll. Type of the method is a number and the default value is 10. You may need to increase or decrease the value to make the scrollspy work properly.
Events
'activate' event fires whenever a new item becomes activated by the scrollspy
You may download all the HTML, CSS, JS and image files used in our tutorials here.
Previous: Twitter Bootstrap Dropdown JavaScript Plugin
Next:
Twitter Bootstrap carousel tutorial