jQuery scrollTop()

The jQuery scrollTop method is used to set or return the vertical scrollbar position of the selected element. It provides the current vertical position of the selected element when it is used to return the position, and it sets the vertical scrollbar position of the selected element when it is used to set the position.

Syntax

When used to return the vertical scrollbar position:

$(selector).scrollTop()

When used to set the vertical scrollbar position:

$(selector).scrollTop(position)

Position:

  • This is a mandatory parameter that is used to specify the vertical scrollbar position to be set.
  • This parameter accepts values in pixels.
  • The top position of the scrollbar is on the top and is termed as position 0.

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("div").scrollTop() + " px");
});
});
</script>
</head>
<body>
<div style="border:3px solid red;width:250px;height:200px;overflow:auto">
<p>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
</p>
</div><br>
<button>Return the vertical position of the scrollbar</button>
<p>Move the scrollbar down and click the button again.</p>
</body>
</html>

Example2:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>scrollTop demo</title>
<style>
div.demo {
border:3px solid red;width:250px;height:200px;overflow:auto
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="demo">
<p>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
Onion <br>
Tomato <br>
</p>
</div>
<script>
$( "div.demo" ).scrollTop( 100);
</script>
</body>
</html>
Please follow and like us:
Content Protection by DMCA.com