Open In App

How to scroll automatically to a particular element using JQuery?

The task is to scroll to a particular element automatically. Below are the approaches:

Approach 1:



Example 1: This example uses the approach discussed above.




<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        How to scroll automatically to a particular element.
    </title>
    <style>
        #GFG_DOWN {
            margin-top: 370px;
        }
    </style>
    <script src=
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
    <p id="GFG_UP" 
       style="font-size: 15px;
              font-weight: bold;">
    </p>
    <button onclick="gfg_Run()">
        Click Here
    </button>
    <p id="GFG_DOWN"
       style="color:green;
              font-size: 30px; 
              font-weight: bold;">
        This is element.
    </p>
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        el_up.innerHTML = 
"Click on the button to scroll to the particular element.";
  
        function gfg_Run() {
            $(window).scrollTop($('#GFG_DOWN').position().top);
        }
    </script>
</body>
  
</html>

Output:

Approach 2:



Example 2: This example uses the approach discussed above.




<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        How to scroll automatically to a particular element.
    </title>
    <style>
        #GFG_DOWN {
            margin-top: 400px;
        }
    </style>
    <script src=
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">  
            GeeksForGeeks  
        </h1>
    <p id="GFG_UP" 
       style="font-size: 15px; font-weight: bold;">
    </p>
    <button onclick="gfg_Run()">
        Click Here
    </button>
    <p id="GFG_DOWN" 
       style="color:green; 
              font-size: 30px;
              font-weight: bold;">
        This is element.
    </p>
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        el_up.innerHTML = 
"Click on the button to scroll to the particular element.";
  
        function gfg_Run() {
            $('html, body').animate({
                scrollTop: $("#GFG_DOWN").offset().top
            }, 500);
        }
    </script>
</body>
  
</html>

Output:

jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.


Article Tags :