HTML DOM scrollTop property
Example
Slide the scrollbar to get the distance from the element's scrollbar to the element's left or top:
const
element
=
document
.
getElementById
(
"
myDIV
"
)
;
let
x
=
elmnt
.
scrollLeft
;
let
y
=
elmnt
.
scrollTop
;
Try it »
Definition and Usage
The scrollTop property can get or set the number of pixels an element's content is scrolled vertically.
The scrollTop value of an element measures the distance from the top of the element's content (scrolled up) to the top of its viewport's visible content. When an element's content does not produce a vertical scrollbar, its scrollTop value is 0.
On systems using display scaling, scrollTop may be a fractional number.
Browser support
| property | |||||
|---|---|---|---|---|---|
| scrollTop | Yes | Yes | Yes | Yes | Yes |
Syntax
Get the scrollTop property value:
// Get the number of scrolled pixels
var intElemScrollTop = element.scrollTop
intElemScrollTop is an integer representing the number of pixels the element's content is scrolled upward.
Set the scrollLeft property value:
// Set the scroll distance
element.scrollTop = intValue;
scrollTop can be any integer, however:
- If an element cannot be scrolled (for example, it does not overflow, or this element has a "non-scrollable" attribute),
scrollTopwill be set to0. - Settings
scrollTopIf the value is less than 0,scrollTopit is set to0 - If a value beyond the scrollable range of this container is set,
scrollTopit is set to the maximum value.
Technical Details
| Return Value: | Returns an integer representing the number of pixels the element's content is scrolled vertically. |
|---|
More examples
Example
Set the element with id "myDIV" to scroll 50 pixels horizontally and 10 pixels vertically:
const
element
=
document
.
getElementById
(
"
myDIV
"
)
;
element
.
scrollLeft
=
50
;
element
.
scrollTop
=
10
;
Try it »
Example
Set the element with id "myDIV" to scroll 50 pixels horizontally and 10 pixels vertically each time the button is clicked:
var
elmnt
=
document
.
getElementById
(
"
content
"
)
;
function
getFunction
(
)
{
var
x
=
elmnt
.
scrollWidth
;
var
y
=
elmnt
.
scrollHeight
;
}
function
setFunction
(
)
{
elmnt
.
style
.
height
=
y
.
scrollHeight
"
px
"
;
elmnt
.
style
.
width
=
y
.
scrollWidth
"
px
"
;
}
Try it »
Element object