Bootstrap Scrollspy Plugin

The scrollspy is a navigation mechanism which checks scrollable area on webpage and activates a link to inform where the scrollbar is situated in a list. It automatically update targets on navigation bar based on scroll position. If we have different sections of a page which contain large amount of data, then we can use links to jump to a specific section in the scrollable area. It specifies the visitors, on which page they are currently.

It works in two directions: one is, navigates to an item and second, shows the displayed item in the scrollable area in the navigation list. The advantage of using this plugin is, we can save the time and content can be accessible more easily to the users.

also read:

The following examples demonstrate use of different techniques used for implementing the scrollspy in Bootstrap. If you have any questions about bootstrap scrollspy plugin, please write it in the comments section.

Bootstrap Scrollspy via Data Attributes

We can easily create scrollspy behavior to navigation by using data-spy=”scroll” in the target division in which element is to be spied. We use the attribute, data-target to link to the navigation ID which uses the ID or class of the parent element within the .nav component.
The following is an example:

<!DOCTYPE html>
<head>
<title>Bootstrap Example</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>ScrollSpy via Data Attributes</h2>
<nav id="navbar-example" class="navbar navbar-default navbar-static" role="navigation">
   <div class="navbar-header">
      <button class="navbar-toggle" type="button" data-toggle="collapse"
         data-target=".bs-js-navbar-scrollspy">
         <span class="sr-only">Toggle navigation</span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Programming Tutorial</a>
   </div>
   <div class="collapse navbar-collapse bs-js-navbar-scrollspy">
      <ul class="nav navbar-nav">
         <li><a href="#myval">HTML</a></li>
         <li><a href="#myval1">CSS</a></li>
         <li class="dropdown">
            <a href="#" id="navbarDrop1" class="dropdown-toggle"
               data-toggle="dropdown">JS Frameworks<span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
               <li><a href="#myval2" tabindex="-1">JavaScript</a></li>
               <li><a href="#myval3" tabindex="-1">JQuery</a></li>
            </ul>
         </li>
      </ul>
   </div>
</nav>
<div data-spy="scroll" data-target="#navbar-example" data-offset="0"
   style="height:200px;overflow:auto; position: relative;">
   <h4 id="myval">HTML</h4>
   <p>HTML stands for Hyper Text Markup Language. A markup language is a set of markup tags.HTML documents contain HTML tags and plain textHTML documents are also called web pages. HTML elements form the building blocks of all websites. HTML allows images and objects to be embedded and can be used to create interactive forms.It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. </p>
   <h4 id="myval1">CSS</h4>
   <p>CSS stands for Cascading Style Sheets. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors, spacing) to Web documents.Styles define how to display HTML elements.External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files.</p>
   <h4 id="myval2">JavaScript</h4>
   <p>JavaScript is the programming language of the Web. JavaScript is the most popular programming language in the world.All modern HTML pages are using JavaScript.The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements.JavaScript can manipulate the DOM (change HTML contents).It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more. </p>
   <h4 id="myval3">JQuery</h4>
   <p>jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming.jQuery is easy to learn. jQuery is a lightweight, "write less, do more", JavaScript library.The purpose of jQuery is to make it much easier to use JavaScript on your website.</p>
</div>
</body>
</html>

Bootstrap Scrollspy via Data Attributes Example

Bootstrap Scrollspy via JavaScript

We can also invoke scrollspy manually by using the scrollspy()method.Use id or class selector of the nav bar in the JavaScript code.

<!DOCTYPE html>
<head>
<title>Bootstrap Example</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<script>
$(document).ready(function(){
    $("#My-Demo").scrollspy();
});
</script>
</style>
<body>
    <div class="container">
    <h2>ScrollSpy via JavaScript</h2>
	     <nav id="#My-Demo" class="navbar navbar-default" role="navigation">
	    <div class="navbar-header">
	    <button type="button" class="navbar-toggle" data-toggle="collapse"
	       	data-target="#navbarCollapse">
	        <span class="sr-only">Toggle navigation</span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	        <span class="icon-bar"></span>
	     </button>
	            <a class="navbar-brand" href="#">Programming Tutorial</a>
	        </div>
	        <div class="collapse navbar-collapse" id="navbarCollapse">
	            <ul class="nav navbar-nav">
	                <li class="active"><a href="#myval">HTML</a></li>
                    <li><a href="#myval1">CSS</a></li>
	                <li class="dropdown"><a href="#" class="dropdown-toggle"
	                  data-toggle="dropdown">JS Frameworks<span class="caret"></span></a>
			<ul class="dropdown-menu">
				<li><a href="#myval2" tabindex="-1">JavaScript</a></li>
				<li><a href="#myval3" tabindex="-1">JQuery</a></li>
			</ul>
	                </li>
	            </ul>
	        </div>
	    </nav>
    <div data-spy="scroll" data-target="#My-Demo" data-offset="0"
	   style="height:200px;overflow:auto; position: relative;">
	   <h4 id="myval">HTML</h4>
	   <p>HTML stands for Hyper Text Markup Language. A markup language is a set of markup tags.HTML documents contain HTML tags and plain textHTML documents are also called web pages.HTML elements form the building blocks of all websites. HTML allows images and objects to be embedded and can be used to create interactive forms.It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items.
	   </p>
	   <h4 id="myval1">CSS</h4>
	   <p>CSS stands for Cascading Style Sheets. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors, spacing) to Web documents.Styles define how to display HTML elements.External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files.</p>

	   <h4 id="myval2">JavaScript</h4>
	   <p>JavaScript is the programming language of the Web. JavaScript is the most popular programming language in the world.
	   	  All modern HTML pages are using JavaScript.The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements.JavaScript can manipulate the DOM (change HTML contents).It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more.
	   </p>
	   <h4 id="myval3">JQuery</h4>
	   <p>jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming. jQuery is easy to learn. jQuery is a lightweight, "write less, do more", JavaScript library.The purpose of jQuery is to make it much easier to use JavaScript on your website.
	   </p>
   </div>
</div>
</body>
</html>

Bootstrap Scrollspy via JavaScript Example

Bootstrap Scrollspy Options

There are certain options which are passed to scrollspy() method via data attributes or JavaScript, which customize the functionality of a scrollspy.

OptionTypeDefault ValueDescription
offsetnumber10It determines number of pixels to offset from the top when calculating position of scroll.

Bootstrap Scrollspy Methods

When we want to add or remove the elements from the DOM, we need to call the refresh method as shown in the following example:

<!DOCTYPE html>
<head>
<title>Bootstrap Example</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
   $(document).ready(function(){
      removeSection=function(e){
         $(e).parents(".section").remove();
            $('[data-spy="scroll"]').each(function(){
               var $spy=$(this).scrollspy('refresh')
         });
      }
      $("#my-demo").scrollspy();
   });
</script>
</head>
<body>
<div class="container">
<h2>ScrollSpy using Methods</h2>
<nav id="my-demo" class="navbar navbar-default navbar-static" role="navigation">
   <div class="navbar-header">
      <button class="navbar-toggle" type="button" data-toggle="collapse"
         data-target=".bs-js-navbar-scrollspy">
         <span class="sr-only">Toggle navigation</span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Programming Tutorial</a>
   </div>
   <div class="collapse navbar-collapse bs-js-navbar-scrollspy">
      <ul class="nav navbar-nav">
         <li class="active"><a href="#myval">HTML</a></li>
         <li><a href="#myval1">CSS</a></li>
         <li class="dropdown">
            <a href="#" class="dropdown-toggle"
               data-toggle="dropdown">JS Frameworks<span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
               <li><a href="#myval2" tabindex="-1">JavaScript</a></li>
               <li><a href="#myval3" tabindex="-1">JQuery</a></li>
            </ul>
         </li>
      </ul>
   </div>
</nav>
<div data-spy="scroll" data-target="#my-demo" data-offset="0"
   style="height:200px;overflow:auto; position: relative;">
   <div class="section">
   <h4 id="myval">HTML<small><a href="#" onclick="removeSection(this);">
         &times; Remove this section</a></small></h4>
   <p>HTML stands for Hyper Text Markup Language. A markup language is a set of markup tags.
      HTML documents contain HTML tags and plain textHTML documents are also called web pages.
      HTML elements form the building blocks of all websites. HTML allows images and objects to be embedded and can be used to create interactive forms.
      It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items.
   </p>
   </div>

   <h4 id="myval1">CSS</h4>
   <p>CSS stands for Cascading Style Sheets. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors, spacing) to Web documents.
      Styles define how to display HTML elements.External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files.
   </p>
   <div class="section">
   <h4 id="myval2">JavaScript<small><a href="#" onclick="removeSection(this);">
         &times; Remove this section</a></small></h4>
   <p>JavaScript is the programming language of the Web. JavaScript is the most popular programming language in the world.
   	  All modern HTML pages are using JavaScript.The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements.
      JavaScript can manipulate the DOM (change HTML contents).It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more.
   </p>
   </div>
   <h4 id="myval3">JQuery</h4>
   <p>jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming.
   	  jQuery is easy to learn. jQuery is a lightweight, "write less, do more", JavaScript library.
   	  The purpose of jQuery is to make it much easier to use JavaScript on your website.
   </p>
</div>
</body>
</html>

Bootstrap Scrollspy using Methods Example

Bootstrap Scrollspy Events

Bootstrap provides following event customize the functionality of a scrollspy:

EventDescription
activate.bs.scrollspyIt triggers whenever an item gets activated with the scrollspy.

The following is an example:

<!DOCTYPE html>
<head>
<title>Bootstrap Example</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script>
   $(document).ready(function(){
      removeSection=function(e){
         $(e).parents(".section").remove();
            $('[data-spy="scroll"]').each(function(){
               var $spy=$(this).scrollspy('refresh')
         });
      }
      $("#my-demo").scrollspy();
      $("#my-demo").on('activate.bs.scrollspy',function(){
         var currentSection=$(".nav li.active > a").text();
         $("#activeItem").html("You are viewing: "+currentSection);
      })
   });
</script>
</head>
<body>
<div class="container">
<h2>ScrollSpy using Events</h2>
<nav id="my-demo" class="navbar navbar-default navbar-static" role="navigation">
   <div class="navbar-header">
      <button class="navbar-toggle" type="button" data-toggle="collapse"
         data-target=".bs-js-navbar-scrollspy">
         <span class="sr-only">Toggle navigation</span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
         <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Programming Tutorial</a>
   </div>
   <div class="collapse navbar-collapse bs-js-navbar-scrollspy">
      <ul class="nav navbar-nav">
         <li class="active"><a href="#myval">HTML</a></li>
         <li><a href="#myval1">CSS</a></li>
         <li class="dropdown">
            <a href="#" class="dropdown-toggle"
               data-toggle="dropdown">JS Frameworks<span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
               <li><a href="#myval2" tabindex="-1">JavaScript</a></li>
               <li><a href="#myval3" tabindex="-1">JQuery</a></li>
            </ul>
         </li>
      </ul>
   </div>
</nav>
<div data-spy="scroll" data-target="#my-demo" data-offset="0"
   style="height:200px;overflow:auto; position: relative;">
   <div class="section">
   <h4 id="myval">HTML<small><a href="#" onclick="removeSection(this);">
         &times; Remove this section</a></small></h4>
   <p>HTML stands for Hyper Text Markup Language. A markup language is a set of markup tags.
      HTML documents contain HTML tags and plain textHTML documents are also called web pages.
      HTML elements form the building blocks of all websites. HTML allows images and objects to be embedded and can be used to create interactive forms.
      It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items.
   </p>
   </div>
   <h4 id="myval1">CSS</h4>
   <p>CSS stands for Cascading Style Sheets. Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors, spacing) to Web documents.
      Styles define how to display HTML elements.External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files.
   </p>
   <div class="section">
   <h4 id="myval2">JavaScript<small><a href="#" onclick="removeSection(this);">
         &times; Remove this section</a></small></h4>
   <p>JavaScript is the programming language of the Web. JavaScript is the most popular programming language in the world.
   	  All modern HTML pages are using JavaScript.The HTML DOM (the Document Object Model) is the official W3C standard for accessing HTML elements.
      JavaScript can manipulate the DOM (change HTML contents).It is the language for HTML, for the Web, for computers, servers, laptops, tablets, smart phones, and more.
   </p>
   </div>
   <h4 id="myval3">JQuery</h4>
   <p>jQuery is a JavaScript Library. jQuery greatly simplifies JavaScript programming.
   	  jQuery is easy to learn. jQuery is a lightweight, "write less, do more", JavaScript library.
   	  The purpose of jQuery is to make it much easier to use JavaScript on your website.
   </p>
</div>
<hr>
      <h4 id="activeItem" class="text-info"></h4>
</div>
</body>
</html>

Bootstrap Scrollspy using Events Example

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*