<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <section id='top'> Header section <p> <a href='#bottom'> Click to scroll down </a> </p> </section> <p> <img src='../../images/theme/easy-image-resizer.jpg' style='width: 50%; margin: 200px 0 500px;'> </p> <section id='bottom'> This is the footer section. <p> <a href='#top' Click to scroll up </a> </p> </section> </body> <script> $('a').click(function (e) { $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top }, 1000); }); </script> </html>
I have two sections in the above markup. One section is on the top for header and another section at the bottom for footer. Each section has a link or anchor tag with the hash value pointing to a section.
<a href='#bottom'></a>
and
<a href='#top'></a>
Clicking the links will scroll the page up and down. To give it a smooth scrolling effect, I have written a small jQuery script.
I am using jQuery .animate() method for a smooth scroll, with a duration of 1000 milliseconds or (1 second). You can change the delay to 2000 or more, depending upon your requirement.
👉 Here's another animation example in jQuery. I am sure you will like this.
Within the animate() method, I have added the scrollTop method. This method takes a parameter as position, to where it will scroll, vertically. The position is the anchor link’s location, which is extracted using the .offset() method.
scrollTop: $($(this).attr('href')).offset().top
Simplifying this further,
When you click the <a> tag, the scrollTop method is called with the anchor links (<a>) location and it animatedly or smoothly scroll to that location, taking a sweet time of 1000 milliseconds (instead of reaching the location instantly). Its that simple.
Note: Not just top and bottom, you can use the same method to scroll to any location of a web page. For example,
<script> $('a').click(function (e) { $('html, body').animate({ scrollTop: $('#theBird').offset().top // Use element id to get element's location. }, 1000); }); </script>
The location now, is extracted using the id of the element.
👉 How to show hide and animate controls (or elements) on a web page using jQuery .animate() method and CSS.