jQuery .scrollTop() sets and gets the vertical position of the scroll bar
Syntax for .scrollTop()(getter)
.scrollTop()(getter)
gets the current vertical position of the scroll bar for the first element in the set of matched elements.
Its return value is the vertical scroll position in pixels.
If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.
The following code gets the scroll top offset.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w ww . j ava 2s . c o m-->
var p = $("p:first");
$("p:last").text( "scrollTop:" + p.scrollTop() );
});
</script>
</head>
<body>
<body>
<p>Hello java2s.com</p>
</body>
</html>
Syntax for .scrollTop(value) (setter)
.scrollTop(value) (setter)
sets the current vertical position of the scroll bar for each of the sets of matched elements.
value
is an integer indicating the new position to set the scroll bar to.
Its return value is the jQuery object, for chaining purposes.
The following code sets the vertical scroll bar value.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from w ww . j av a 2 s . c o m-->
$("div").scrollTop(300);
});
</script>
<style>
div{
width:200px;
height:100px;
overflow:auto;
}
h1 { width:1000px;height:1000px; }
</style>
</head>
<body>
<body>
<div><h1>java2s.com</h1></div>
</body>
</html>