HTML DOM scrollLeft 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 scrollLeft property can read or set the distance from the element's scrollbar to the left of the element.
Note that if the element's content direction is rtl (right-to-left), the scrollbar will be at the far right (where content starts) and the scrollLeft value will be 0. At this point, when you drag the scrollbar from right to left, scrollLeft changes from 0 to a negative number.
On systems using display scaling, scrollLeft may be a fractional number.
Browser support
| property | |||||
|---|---|---|---|---|---|
| scrollLeft | Yes | Yes | Yes | Yes | Yes |
Syntax
Get the scrollLeft property value:
// Get the distance of the scrollbar to the left of the element
var sLeft = element.scrollLeft
sLeft is an integer representing how many pixels the element's scrollbar is from the left of the element.
Set the scrollLeft property value:
// How many pixels the scrollbar scrolled
element.scrollLeft = pixels
scrollLeft can be any integer, however:
- If the element cannot scroll (for example, the element does not overflow), then
scrollLeftthe value is 0. - If a value is assigned to
scrollLeftthat is less than 0,scrollLeftthe value becomes 0. - If a value is assigned to
scrollLeftIf the assigned value is greater than the maximum content width of the element, thenscrollLeftthe value is set to the maximum width of the element.
Technical Details
| Return Value: | Returns an integer representing the number of pixels the element's content is scrolled horizontally. |
|---|
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