Introduction
Bootstrap is one of the most popular HTML, CSS, and JavaScript frameworks for developing responsive, mobile first projects on the web. It provides many ready-to-go components and mobile-friendly styles to facilitate developers' work.
It is very common to include a navbar for navigating different parts in a long page. Bootstap includes a Scrollspy Plugin to automatically update links when we scroll within the page.
Background
Here is an example. When we scroll down the page, the active link of navbar is automatically updated based on which part we are viewing. The page detects the section in the viewport and updates the active link. This feature is called scrollspy.
In following screenshots, the top links switch active links while we scroll down the page.
Using the Code
Steps for how to implement Scrollspy:
- Install bootstrap
- Add navbar and content
- Configure scrollspy
Install bootstrap
Add bootstrap library and CSS into the <head></head>
part of the page:
<head>
...
<!--
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!--
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!--
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
...
</head>
Add navbar and Content
Navbar Part
<div class="bs-docs-sidebar">
<ul class="nav">
<li><a href="#one">hello Bootstrp 3</a></li>
<li><a href="#two">hello jQuery</a></li>
<li><a href="#three">hello ScrollSpy</a></li>
</ul>
</div>
Content Sections
<div id="one">
<h1>This is section one.</h1>
<p>...</p>
</div>
<div id="two">
<h1>This is section two.</h1>
<p>...</p>
</div>
<div id="three">
<h1>This is section three.</h1>
<p>...</p>
</div>
As the basic html structure, we can click the anchor to jump to the content.
Add a dropdown Menu (Optional)
Adding a dropdown submenu is pretty easy.
Add dropdown class to the item.
Add class dropdown-toggle and an attribute data-toggle="dropdown"
to the <a>
tag.
Add a <ul>
element with dropdown-menu class and all submenus.
<li class="dropdown open">
<a href="#" class="dropdown-toggle"
data-toggle="dropdown">hello four</a>
<ul class="dropdown-menu">
<li><a href="#four1">Section 4-1</a></li>
<li><a href="#four2">Section 4-2</a></li>
<li><a href="#four3">Section 4-3</a></li>
</ul>
</li>
Final Result
Configure scrollspy
Way 1 - Via Pure CSS
Add two attributes to body: data-spy="scroll"
and data-target="target"
. Here, target
can be a class or element id of the navbar.
<body data-spy="scroll" data-target=".bs-docs-sidebar">...</body>
Way 2 - Via jquery
Add scrollspy()
method to content.
$(function(){
$('.bs-docs-sidebar').scrollspy();
});
History
- October 29, 2015: First version posted