EN
JavaScript - get div scroll left
0 points
In this article, we would like to show you how to get the div element scrollLeft property using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.scrollLeft;
In this example, we get the handle to scrollContainer
element, then we use scrollLeft
property to get the number of pixels that an element's content is scrolled horizontally. The value of scrollLeft
property is displayed as the output
element textContent
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
#scroll-container {
6
width: 100px;
7
border: 1px solid lightgray;
8
overflow-x: scroll;
9
}
10
11
#text {
12
width: 250px;
13
}
14
15
#output {
16
padding: 1rem 0;
17
}
18
</style>
19
</head>
20
<body>
21
<div id='scroll-container'>
22
<div id='text'>This is an example text...</div>
23
</div>
24
<div id='output'>scrollLeft: 0</div>
25
<script>
26
27
const scrollContainer = document.querySelector('#scroll-container');
28
const output = document.querySelector('#output');
29
30
scrollContainer.addEventListener('scroll', event => {
31
output.textContent = 'scrollLeft: ' + scrollContainer.scrollLeft;
32
});
33
34
</script>
35
</body>
36
</html>