The scrollspy Jquery plugin is a navigation mechanism that automatically highlights navigation links based on scroll position to tell the visitor where they are.
Project structure
scrollspy/
┣ plugins/
┃ ┗ scrollspy.min.js
┗ index.html
index.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
html, body {
margin: 0;
padding: 0;
}
.fixed {
position: fixed;
top: 0;
}
.navigation {
width: 100%;
background-color: white;
height: 75px;
}
.navigation ul {
list-style: none;
margin: 20px 0 0 0;
padding: 0;
}
.navigation ul li {
display: inline-block;
margin: 0 0 0 30px;
padding: 0;
}
.navigation ul li.active a {
border-bottom-width: 4px;
border-bottom-style: solid;
border-bottom-color: inherit;
}
.navigation ul li.blue {
border-bottom-color: #0071c5;
}
.navigation ul li.green {
border-bottom-color: #c4d600;
}
.navigation ul li.orange {
border-bottom-color: #fc4c02;
}
.navigation ul li.yellow {
border-bottom-color: #f3d54e;
}
.navigation ul li a:link,
.navigation ul li a:visited,
.navigation ul li a:active,
.navigation ul li a:hover,
.navigation ul li a:focus {
color: #333;
text-decoration: none;
padding-bottom: 10px;
}
.top-page {
margin-top: 75px;
}
.page {
min-height: 500px;
}
.page.blue {
background-color: #0071c5;
}
.page.green {
background-color: #c4d600;
}
.page.orange {
background-color: #fc4c02;
}
.page.yellow {
background-color: #f3d54e;
}
.my-container{
margin: 0px 20px;
}
</style>
</head>
<body>
<nav class="navigation fixed" id="nav">
<ul>
<li class="blue active"><a href="#page1">Page 1</a></li>
<li class="green"><a href="#page2">Page 2</a></li>
<li class="orange"><a href="#page3">Page 3</a></li>
<li class="yellow"><a href="#page4">Page 4</a></li>
</ul>
</nav>
<div class="my-container">
<div class="page blue top-page" id="page1">
<h1>Page 1</h1>
</div>
<div class="page green" id="page2">
<h1>Page 2</h1>
</div>
<div class="page orange" id="page3">
<h1>Page 3</h1>
</div>
<div class="page yellow" id="page4">
<h1>Page 4</h1>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="plugins/scrollspy.min.js"></script>
<script>
$("#nav").scrollspy({
offset: -75,
animate: true,
duration: 500,
});
</script>
</body>
</html>
scrollspy.min.js you can download zip file below is link to download source code where you will get this plugin file you can download and link as you have seen above example.
Understand scrollspy
there is few options we need to understand
$("#nav").scrollspy({
offset: -75,
animate: true,
duration: 500,
});
offset
This tells the plugin if there is any need to include an offset. default: 0
animate
This tells the plugin whether it should animate the scroll when a link in your menu is click or not. default: false
duration
This is the duration of the animation in milliseconds. default: 1000
Code is tested and it will work 100% for you