jQuery Smooth Scroll to the ID

This article will show you how to do jQuery Smooth Scroll to the ID. There is a lot of ways to use smooth scrolling to the given ID but using jQuery with few lines of code will make it easy. For example, if you click on a tag #hash link, this will help to reach the given ID. Using the below jQuery code you will adjust the speed of scrolling and the animation for that you just need to change to whatever you want, Here I used 600 milliseconds and for animation swing.
Use the below code to use on your website.
HTML
1 2 3 4 5 6 7 |
<a href="#section1">Section 1</a> <a href="#section2">Section 2</a> <a href="#section3">Section 3</a> <br/><br/> <div id="section1">First Element</div> <div id="section2">Second Section</div> <div id="section3">Third Section</div> |
CSS
1 2 3 |
div { height: 100vh; } |
jQuery
1 2 3 4 5 6 7 8 9 10 11 |
$('a[href*="#"]').on('click', function(e) { e.preventDefault() $('html, body').animate( { scrollTop: $($(this).attr('href')).offset().top, }, 600, 'swing' ) }) |
Conclusion:
I hope this article will help you to do the smooth scroll to the given ID with jQuery. If you like this article kindly share it with your friends.
Mraj
Creative Designer & Developer specialist by the spirit and a loving blogger by thoughts. If you have any questions let me drop an email with the article name to the following email id: [email protected]