What is a scrollspy in Bootstrap ?
We have visited many websites where the navigation bars are automatically updated as the user scrolls down the webpage. Scrollspy works according to the scroll position or the position at which the user is currently is seeing. Bootstrap scrollspy targets the navigation bar contents automatically on scrolling the area. In this article, we will see how to implement the scrollspy in Bootstrap. We will implement the scrollspy in 2 ways:
- Horizontal scrollspy
- Vertical scrollspy
We need to import the Bootstrap CDN libraries to use the scrollspy functionality. We will include the libraries from the official bootstrap website. There are a few requirements in order to scrollspy works properly:
- Bootstrap nav component or list group is necessary to include.
- Require position : relative: on the element for which spying is applied, generally in the body tag.
- <a> tag is required that must point to an element with that id.
Implementing horizontal scrollspy: We will create a navbar using a nav tag in our body. The navbar will contain three items. We will use the container class having the heading and some dummy text, which will provide some top padding to ensure that the navbar and container don’t overlap with each other. The navbar should be fixed at the top in order to scrollspy works properly.
Some attributes are added with the elements for the implementation of this feature to the body tag.
<body style="position:relative" data-spy="scroll" data-target=".navbar" data-offset="50">
- data-spy: It is used to spy the current position in which the user is scrolling.
- data-target: This attribute is used to connect the navigation bar with the scrollable area.
- data-offset: This attribute specifies the number of pixels to offset from the top when calculating the position of scroll.
Implementing vertical scrollspy: For vertical Scrollspy, we need a vertical navbar. We have wrapped our contents inside a row for the vertical view of our navbar.
Output: We have provided a margin of 150px if the screen width is less than 810px.