How to use scrollTop () Method and scrollTop (position) using function method in JQuery

In this article, I will explain use of scrollTop () Method and how to use scrollTop (position) method in JQuery.
  • 4813

Introduction

  • scrollTop() method sets or returns the offset(vertical) position of the scrollbar of the first matched elements.
  • The vertical position of the scrollbar is the number of pixels. When the scrollbar is on the far left side, the position is 0.

JQuery CSS scrollTop() method

scrollTop() method returns the vertical position of the scrollbar

Syntax

$(selector).scrollTop()

Example

The following example shows how to scrollTop() method in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("button").click(function () {

            alert("vertical position "+$("div").scrollTop() + " px");

        });

    });

</script>

</head>

<body>

<h3>ScrollTop Method Example</h3>

<div style="border:1px solid black;width:100px;height:150px;overflow:auto;color:red">

Welcome to Csharpcorner! Welcome to Csharpcorner! Welcome to Csharpcorner! Welcome to Csharpcorner!</div>

<button>Click for display the vertical position of the scrollbar</button>

<p>Move the scrollbar down and click the button again.</p>

</body>

</html>

 

Output

 

 scrolltop.jpg

JQuery CSS scrollTop(position) method

scrollTop(position) method sets the vertical position of the scrollbar.

Syntax

$(selector).scrollTop(position)

Example

The following example shows how to scrollTop(position) method in jquery.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

    $(document).ready(function () {

        $("button").click(function () {

            $("div").scrollTop(10);

            alert("set the position of the scroolbar to 10px ");

        });

    });

</script>

</head>

<body>

<h3>ScrollTop(position) Method Example</h3>

<div style="border:1px solid black;width:100px;height:150px;overflow:auto;color:red">

Welcome to Csharpcorner! Welcome to Csharpcorner! Welcome to Csharpcorner! Welcome to Csharpcorner!</div>

<button>Click for set the vertical position of the scrollbar to 10px</button>

</body>

</html>

 

Output

 

 scrooltop position.jpg

Further Readings

You may also want to read these related articles here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.