There are two methods to smoothly scroll a web page after clicking the anchor link which are discussed below:
Method 1: Using scrollIntoView() with the ‘smooth’ behavior: The scrollIntoView() method is used to scroll the view of the user to the element that it is called upon. It contains several options that may be defined to modify the scroll behavior. One of these is ‘behavior’ property. The default value of this property makes the scroll instantly jump to its destination, instead of smoothly scrolling. Setting this value to ‘smooth’ changes this behavior and makes the page scroll smoothly.
The hash portion of the anchor link is first extracted using the hash property and it is selected with the querySelector() method. The scrollIntoView() method is then called on this selected element to smoothly scroll the page to this location.
Method 2: Using jQuery scrollTop() method: The scrollTop() method in jQuery is used to scroll to a particular portion of the page. Animating this method with the available inbuilt animations can make the scroll smoother.
The hash portion of the anchor link is first extracted using the hash property and its position on the page is found out using the offset() method. The scrollTop() method is then called on this hash value to scroll to that location. This method is animated by enclosing it within the animate() method and specifying the duration of the animation to be used in milliseconds. A larger value would make the animation slower to complete than a smaller value. This will smoothly animate all the anchor links on the page when they are clicked.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.