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:
- Get the height of the element by .position().top property.
- Use .scrollTop() method to set the vertical position of the scrollbar equal to the calculated height of the particular element.
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 = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ 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:
-
Before clicking on the button:
-
After clicking on the button:
Approach 2:
- Get the height of the element by .offset().top property.
- Use .animate() method to animate to the element.
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 = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ 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:
-
Before clicking on the button:
-
After clicking on the button:
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.