jQuery scrollTop() Method

jQuery | scrollTop() Method: Learn about the jQuery scrollTop() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 15, 2022

scrollTop() Method

In this tutorial, we'll learn how to scroll to the top of a webpage using the scrollTop() method of jQuery.

You must have visited different websites where once when you are at the end of the page, there is an option to go to the top all in one go. So, if you want to go to the very start of the document again, then you may click on that button. Therefore, it takes you up to the top of the page. This is what the scrollTop() method of jQuery does.

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 pixel 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.

scrollTop() Method 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. Hence, the following example shows how to implement the scrollTop() method in jQuery. When the user goes down the page and then clicks the button, then it will be taken to the top of the page.

jQuery scrollTop() Method Example

<!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>
    <style>
      html, body{
      height: 300%;
      }
    </style>
    <title>Document</title>
  </head>
  
  <body style="background-color: lavender;">
    <h2>jQuery - ScrollTop</h2>
    <hr>
    <br><br>
    <div style="position: fixed; background-color:darkcyan; padding: 0.75%;">
      <p>Click the button to scroll to top of the page.</p>
      <button>ScrollTop</button>
    </div>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button').click(function(){
            $(document).scrollTop('0');
        })
    });
  </script>
</html>

Output:

Example 1: jQuery scrollTop() Method


All jQuery Examples

Comments and Discussions!

Load comments ↻





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