Scrollspy In Bootstrap

In this article we will learn about how to use Scrollspy in our applications.
 
Sometimes bases on business need while designing the website, management/ client want to include some attractive features from UI point of view which makes website better look and feel.
 
So here it One of the most important features in Bootstrap4 scrollspy is available which target the navigation bar contents highlight automatically on the time scrolling the area. so here we will cover the following things,
  • Definition
  • Create Horizentol Scrollspy
  • Create Vertical Scrollspy
  • Summary

Definition

 
Scrollspy is the concept of automatically scrolling Bootstrap navigation menu or list group of items based on scroll position so that it will use to indicate which link is currently in active state.
 
There are two type of scrollspy we can apply: (1-Horizentol Scrollspy, 2-Vertical Scrollspy)
 
For the real implementation Scrollspy uses three attribute,
  1. data-spy
  2. data-target
  3. data-offset
data-spy = "scroll": attribute, This attribute can be used for scrollable area
 
data-target: which we can use with the ID or class of the element of any Bootstrap .navbar component so that it will use to indicate navbar is connected with scrollable area and this currently slected nav links will be highlighted.
 
data-offset: attribute this is use to defines number of pixels which calculates the position of scroll from top.
 

Create Horizentol Scrollspy

 
In this following example I am creating horizontal scrollspy to show how the  nav bar is highlighted at the time of scroll,
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.     <head>  
  4.         <title>Bootstrap Example</title>  
  5.         <meta charset="utf-8">  
  6.             <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.                 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">  
  8.                     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  
  9.                     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>  
  10.                     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>  
  11.                     <style>    
  12.                      body {    
  13.                         position: relative;    
  14.                         }    
  15.                    </style>  
  16.                 </head>  
  17.                 <body data-spy="scroll" data-target=".navbar" data-offset="50">  
  18.                     <nav class="navbar navbar-expand-sm bg-primary navbar-dark fixed-top">  
  19.                         <ul class="navbar-nav">  
  20.                             <li class="nav-item">  
  21.                                 <a class="nav-link" href="#section1">Home</a>  
  22.                             </li>  
  23.                             <li class="nav-item">  
  24.                                 <a class="nav-link" href="#section2">About</a>  
  25.                             </li>  
  26.                             <li class="nav-item">  
  27.                                 <a class="nav-link" href="#section3">Contact </a>  
  28.                             </li>  
  29.                             <li class="nav-item dropdown">  
  30.                                 <a class="nav-link dropdown-toggle" href="#" id="navbardrop" data-toggle="dropdown">    
  31. Services    
  32. </a>  
  33.                                 <div class="dropdown-menu">  
  34.                                     <a class="dropdown-item" href="#section41">Training</a>  
  35.                                     <a class="dropdown-item" href="#section42">Development</a>  
  36.                                 </div>  
  37.                             </li>  
  38.                         </ul>  
  39.                     </nav>  
  40.                     <div id="section1" class="container-fluid bg-success" style="padding-top:70px;padding-bottom:70px">  
  41.                         <h1>Home</h1>  
  42.                         <p>Home Home Home Home Home Home Home Home Home Home Home Home </p>  
  43.                         <p>Home Home Home Home Home Home Home Home Home Home Home Home </p>  
  44.                         <p>Home Home Home Home Home Home Home Home Home Home Home Home </p>  
  45.                     </div>  
  46.                     <div id="section2" class="container-fluid bg-warning" style="padding-top:70px;padding-bottom:70px">  
  47.                         <h1>About</h1>  
  48.                         <p>About About About About About About About About About</p>  
  49.                         <p>About About About About About About About About About</p>  
  50.                         <p>About About About About About About About About About</p>  
  51.                         <p>About About About About About About About About About</p>  
  52.                     </div>  
  53.                     <div id="section3" class="container-fluid bg-secondary" style="padding-top:70px;padding-bottom:70px">  
  54.                         <h1>Contact</h1>  
  55.                         <p>Contact Contact Contact</p>  
  56.                         <p>Contact Contact Contact</p>  
  57.                         <p>Contact Contact Contact</p>  
  58.                         <p>Contact Contact Contact</p>  
  59.                         <p>Contact Contact Contact</p>  
  60.                         <p>Contact Contact Contact</p>  
  61.                         <p>Contact Contact Contact</p>  
  62.                     </div>  
  63.                     <div id="section41" class="container-fluid bg-danger" style="padding-top:70px;padding-bottom:70px">  
  64.                         <h1>Training</h1>  
  65.                         <p>HTML, CSS, BootStrap, JavaScript, JQuery C#</p>  
  66.                         <p>HTML, CSS, BootStrap, JavaScript, JQuery C#</p>  
  67.                         <p>HTML, CSS, BootStrap, JavaScript, JQuery C#</p>  
  68.                     </div>  
  69.                     <div id="section42" class="container-fluid bg-info" style="padding-top:70px;padding-bottom:70px">  
  70.                         <h1>Development</h1>  
  71.                         <p>Software Development</p>  
  72.                         <p>Website Development</p>  
  73.                         <p>Consultant & Placement</p>  
  74.                         <p>Software Development</p>  
  75.                         <p>Website Development</p>  
  76.                         <p>Consultant & Placement</p>  
  77.                     </div>  
  78.                 </body>  
  79.             </html>   
It will show the result as  in the following image,
 
Scrollspy In Bootstrap
 
Code Explanation
 
As above we have seen that mainly three attributes are required for scrollspy. The  data-spy="scroll" attribute is used to show  the element as the scrollable area. In general this is used for <body element>. But we can use at any tag element. data-target=".navbar": this attribute is used with the value of nav bar element id or the class name of the navigation bar (.navbar).
 
This is use to make sure that the navbar element is connected with the scrollable area. data-offset="50": This attribute is used to specifies the number of pixels from top when we calculate the position of scroll. This data-offset attribute is useful when you think that the given links which is inside the navbar changes the active state as soon as possible
when go to the scrollable elements area. This attribes Default value is 10 pixels.
 
Note
The important point is scrollable elements is mandatory to match the Id of the given links inside the navbar's list items (<div id="section1"> matches <a href="#section1">).
 

Create Vertical Scrollspy

 
In this following example I am creating Vertical scrollspy to how the highlighted nav bar at the time of scroll,
  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.     <head>  
  4.         <title>Bootstrap Example</title>  
  5.         <meta charset="utf-8">  
  6.             <meta name="viewport" content="width=device-width, initial-scale=1">  
  7.                 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">  
  8.                     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  
  9.                     <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>  
  10.                     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>  
  11.                     <style>    
  12.                      body {    
  13.                         position: relative;    
  14.                         }    
  15.                         ul.nav-pills {    
  16.                            top: 20px;    
  17.                            position: fixed;    
  18.                            }    
  19.                         div.col-8 div {    
  20.                            height: 300px;    
  21.                            }    
  22.                      </style>  
  23.                 </head>  
  24.                 <body data-spy="scroll" data-target="#myScrollspy" data-offset="1">  
  25.                     <div class="container-fluid">  
  26.                         <div class="row">  
  27.                             <nav class="col-sm-3 col-4" id="myScrollspy">  
  28.                                 <ul class="nav nav-pills flex-column">  
  29.                                     <li class="nav-item">  
  30.                                         <a class="nav-link active" href="#section1">Home</a>  
  31.                                     </li>  
  32.                                     <li class="nav-item">  
  33.                                         <a class="nav-link" href="#section2">About</a>  
  34.                                     </li>  
  35.                                     <li class="nav-item">  
  36.                                         <a class="nav-link" href="#section3">Contact</a>  
  37.                                     </li>  
  38.                                     <li class="nav-item dropdown">  
  39.                                         <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#">Services</a>  
  40.                                         <div class="dropdown-menu">  
  41.                                             <a class="dropdown-item" href="#section41">Training</a>  
  42.                                             <a class="dropdown-item" href="#section42">Development</a>  
  43.                                             <a class="dropdown-item" href="#section43">Placement</a>  
  44.                                         </div>  
  45.                                     </li>  
  46.                                 </ul>  
  47.                             </nav>  
  48.                             <div class="col-sm-9 col-8">  
  49.                                 <div id="section1" class="bg-success">  
  50.                                     <h1>Home</h1>  
  51.                                     <p>Home!</p>  
  52.                                     <p>Home!</p>  
  53.                                 </div>  
  54.                                 <div id="section2" class="bg-warning">  
  55.                                     <h1>About</h1>  
  56.                                     <p>About</p>  
  57.                                 </div>  
  58.                                 <div id="section3" class="bg-secondary">  
  59.                                     <h1>Contact Us</h1>  
  60.                                     <p>Contact Us</p>  
  61.                                 </div>  
  62.                                 <div id="section41" class="bg-danger">  
  63.                                     <h1>Training</h1>  
  64.                                     <p>Training</p>  
  65.                                 </div>  
  66.                                 <div id="section42" class="bg-info">  
  67.                                     <h1>Development</h1>  
  68.                                     <p>Development</p>  
  69.                                 </div>  
  70.                                 <div id="section42" class="bg-primary">  
  71.                                     <h1>Placement</h1>  
  72.                                     <p>Industry Placement</p>  
  73.                                 </div>  
  74.                             </div>  
  75.                         </div>  
  76.                     </div>  
  77.                 </body>  
  78.             </html>    
It will show the result as following image,
 
Scrollspy In Bootstrap
 
Note
As we did scrollspy both horizento and vertical using Via data-* Attributes the same thing we can do that using programming java script. Then for that we need to use very small code,
  1. <script>  
  2.    $(document).ready(function(){  
  3.       $('body').scrollspy({target: ".navbar", offset: 50});  
  4.    });  
  5. </script>  
The above method will work with class. If we want to use Id in java script then use the following code
  1. $(document).ready(function(){  
  2.    $('body').scrollspy({ target: '#myNavbarId',offset: 50 })  
  3. });  
  4. </script>  
we can do the scrollspy on nested items and on lis-group item
 

Methods

 
It have 2 methods which is used based on business need
  • .scrollspy('refresh')
  • .scrollspy('dispose')
  1. $('[data-spy="scroll"]').each(function () {  
  2.    var $spy = $(this).scrollspy('refresh')  
  3. })  
Events
 
This event is used to fires on the time of scroll the element when a new item will be activated using the scrollspy.
  1. $(document).ready(function() {  
  2.     removeSection = function(e) {  
  3.         $(e).parents(".section").remove();  
  4.         $('[data-spy="scroll"]').each(function() {  
  5.             var $spy = $(this).scrollspy("refresh");  
  6.         });  
  7.     }  
  8.     $(".scroll-area").scrollspy({  
  9.         target: "#myNavbar"  
  10.     });  
  11.     $(".scroll-area").on("activate.bs.scrollspy"function() {  
  12.         var currentItem = $(".nav a.active:last").text();  
  13.         $("#info").empty().html("Currently you are viewing - " + currentItem);  
  14.     })  
  15. });  

Summary

 
Congratulations on following the steps. Whenever you're using a navigation menu on your application, you can implement a Bootstrap scrollspy, so that when you scroll the page either up or down, the navigation menu gets updated by the scrollspy. I hope you liked this tutorial and please share it with others. Do you have any suggestions or additions? Please mention below in the comment section.
 
Thanks for taking your valuable time to read the full article.


Similar Articles