EN
JavaScript - get div scroll top
0 points
In this article, we would like to show you how to get the div element scrollTop property using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.scrollTop;
In this example, we get the handle to scrollContainer
element, then we use scrollTop
property to get the number of pixels that an element's content is scrolled vertically. The value of scrollTop
property is displayed as the output
element textContent
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
#scroll-container {
6
overflow: scroll;
7
height: 150px;
8
width: 200px;
9
}
10
11
#output {
12
padding: 1rem 0;
13
}
14
</style>
15
</head>
16
<body>
17
<div id='scroll-container'>
18
<p>Example text...</p>
19
<p>Example text...</p>
20
<p>Example text...</p>
21
<p>Example text...</p>
22
<p>Example text...</p>
23
</div>
24
<div id='output'>scrollTop: 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 = 'scrollTop: ' + scrollContainer.scrollTop;
32
});
33
34
</script>
35
</body>
36
</html>