×

jQuery Tutorial

jQuery Examples

jQuery Practice

Smooth scrolling when clicking an anchor link using jQuery

Let's see how to scroll smoothly when an anchor tag is clicked, using jQuery?
Submitted by Pratishtha Saxena, on November 22, 2022

Generally, we use direct scrolling when moving from one section of the document to the other section. It can be navigation either between different sections or even from the bottom of the page to the top. Hence, to perform this, we'll use – the jQuery scrollTop() method. This method specifically scrolls from bottom to top.

The scrollTop() method helps to set or return the scroll bar position for the selected elements in jQuery. The value of the scroll bar position will be zero pixels if the vertical scroll bar is at the top, i.e., it cannot scroll up anymore. This method will reach you up to the point where the position of the scroll bar is mentioned. If the scrollbar position is set to 0px – it will take you to the top.

Syntax:

$(selector).scrollTop(position);
$(selector).scrollTop();

Therefore, this method takes in the scrollbar position as its parameter. Here, the position of the scroll bar can be specified. If the position is not specified, then this method will return the current position of the scroll bar.

The following example shows when the anchor link at the bottom of the page is clicked, its takes back to the top of the document.

jQuery code for smooth scrolling when clicking an anchor link

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      html, body{
      height: 100%;
      }
      div{
      height: 100%;
      background-color: lavender;
      }
    </style>
  </head>
  
  <body>
    <h2>Smooth scrolling when clicking an anchor link</h2>
    <p>Click the anchor tag (at the bottom) to have a smooth scroll back to top</p>
    <h1>THE TOP</h1>
    <div></div>
    <br><br>
    <a href="#example" style="font-size: x-large;">Go to TOP again</a>
    <br><br>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('a').click(function(){
            $(document).scrollTop('0');
        });
    });
  </script>
</html>

Output:

Example 1: Smooth scrolling when clicking an anchor link using jQuery Example 2: Smooth scrolling when clicking an anchor link using jQuery




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.