Scrollspy

by Santosh Thakur

HTML

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="collapse navbar-collapse" id="myNavbar">
  <ul class="nav navbar-nav">
    <li><a href="#section1">Section 1</a></li>
    <li><a href="#section2">Section 2</a></li>
    <li><a href="#section3">Section 3</a></li>
  </ul>
</div>

<br><br>
<br>
<br>
<br>
<br>


<div id="section1" class="container-fluid">
  <h1>Section 1</h1>
  <p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<div id="section2" class="container-fluid">
  <h1>Section 2</h1>
  <p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>
<div id="section3" class="container-fluid">
  <h1>Section 3</h1>
  <p>Click on the different Section links in the navbar to see the smooth scrolling effect.</p>
</div>

<br><br>
<br>
<br>
<br>
<br>
<br><br>
<br>
<br>
<br>
<br>

JavaScript

$(document).ready(function(){
  $('body').scrollspy({target: ".navbar", offset: 50});   

  $("#myNavbar a").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      // Store hash
      var hash = this.hash;

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){
   
        window.location.hash = hash;
      });
    }  // End if
  });
});