EN
JavaScript - onscroll event example
3 points
In this article, we would like to show you how to use onscroll
event in JavaScript.
Quick solution:
xxxxxxxxxx
1
<div id="my-element" onscroll="handleScroll()">
2
<!-- div body here... -->
3
</div>
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.addEventListener('scroll', function() {
4
console.log('onscroll event occurred.');
5
});
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.onscroll = function() {
4
console.log('onscroll event occurred.');
5
};
Note: it is very important to work on element that has scrollable content to handle
onscroll
event.
There are three common ways how to use onscroll
event:
- with event listener,
- with element attribute,
- with element property.
To enable content scrolling, example elements to have assigned height
and overflow
styles.
In this section, we want to show how to use scroll
event on div
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
body {
7
height: 100px;
8
}
9
10
div {
11
border: 1px solid black;
12
width: 150px;
13
height: 80px;
14
overflow: scroll;
15
}
16
17
</style>
18
</head>
19
<body>
20
<div id="my-element">
21
Scroll the element.
22
Scroll the element.
23
Scroll the element.
24
Scroll the element.
25
Scroll the element.
26
Scroll the element.
27
</div>
28
<script>
29
30
var myElement = document.querySelector('#my-element');
31
32
myElement.addEventListener('scroll', function() {
33
console.log('onscroll event occurred.');
34
});
35
36
</script>
37
</body>
38
</html>
In this section we want to show how to use onscroll
event on div
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
body {
7
height: 100px;
8
}
9
10
div {
11
border: 1px solid black;
12
width: 150px;
13
height: 80px;
14
overflow: scroll;
15
}
16
17
</style>
18
</head>
19
<body>
20
<div onscroll="handleScroll()">
21
Scroll the element.
22
Scroll the element.
23
Scroll the element.
24
Scroll the element.
25
Scroll the element.
26
Scroll the element.
27
</div>
28
<script>
29
30
function handleScroll(){
31
console.log('onscroll event occurred.');
32
}
33
34
</script>
35
</body>
36
</html>
In this section, we want to show how use onscroll
event on div
element via property.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
body {
7
height: 100px;
8
}
9
10
div {
11
border: 1px solid black;
12
width: 150px;
13
height: 80px;
14
overflow: scroll;
15
}
16
17
</style>
18
</head>
19
<body>
20
<div id="my-element">
21
Scroll the element.
22
Scroll the element.
23
Scroll the element.
24
Scroll the element.
25
Scroll the element.
26
Scroll the element.
27
</div>
28
<script>
29
30
var myElement = document.querySelector('#my-element');
31
32
myElement.onscroll = function() {
33
console.log('onscroll event occurred.');
34
};
35
36
</script>
37
</body>
38
</html>