scrollTop() method for window in Jquery

Date Published: 10/05/2020Published By: JaiSchool

scrollTop is a method of the window in Jquery. This method examines how much you have scrolled a web page in the browser. It will return the distance in pixels from the top of the scrollbar track to the scrollbar thumb.

And you can also define in its parameter that how much the web page should be scrolled vertically by giving value in its parameter. Example-1 to get position and example-2 to set position vertically.

distance in pixels from the top of the scrollbar track to the scrollbar thumb - jaischool.com

Get scrollbar position

<!DOCTYPE html>
<html>
<head>
  <title>scrollTop()</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="height:2000px;">

<button style="position:fixed;top:0;left:0;padding;20px;font-size:25px;">check</button>

<center><img src="https://jaischool.com/wp-content/uploads/2019/12/Jaischool.com_-e1575352026662.png"></center>

<script>
$(document).ready(function(){
   $("button").click(function(){
   var distance=$(window).scrollTop();
   alert(distance);
});
});
</script>

</body>
</html>

Set scrollbar position

You can also give value in its parameter to define vertical position of the scrollbar thumb.

<!DOCTYPE html>
<html>
<head>
  <title>scrollTop()</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body style="height:2000px;">

<button style="position:fixed;top:0;left:0;padding;20px;font-size:25px;">scroll page 150px top</button>

<center><img src="https://jaischool.com/wp-content/uploads/2019/12/Jaischool.com_-e1575352026662.png"></center>

<script>
$(document).ready(function(){
   $("button").click(function(){
   $(window).scrollTop("150");
});
});
</script>

</body>
</html>