Smooth scrolling effect with Jquery when clicking an anchor link

In this snippet we will learn how to create a smooth scrolling effect with Jquery. By this way, when we use the hash tag to move to another element will working smoothly and support all browsers.

Step 1: Add codes below into your Head tag

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("a").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      const hash = this.hash;
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){
        window.location.hash = hash;
      });
    }
  });
});
</script>
Copy this code

In the codes above, we using jQuery's animate() method to add smooth page scroll, and time to scroll is 1000 milliseconds (1 second).

Step 2: Create scrolling element, in the example below, we have two elements.

<div id="section1">
 <h2>Section 1</h2>
 <a href="#section2">Click here to Scroll to Section 2</a>
</div>
<div id="section2">
 <h2>Section 2</h2>
 <a href="#section1">Click here to Scroll to Section 1</a>
</div>
Copy this code

Notice: Please pay attention for the id and href attributes in the codes above.

Step 3: Add the CSS codes for the HTML elements.

body {
 color:#fff;
 font-size: 16px;
}
a{
 color:#fff;
}
#section1 {
 height: 600px;
 padding:20px;
 background-color: rgb(247, 63, 63);
}
#section2 {
 height: 600px;
 padding:20px;
 background-color: rgb(99, 140, 252);
}
Copy this code


© 2019 4codev

Created with love by Sil.