EN
JavaScript - wheel event example
0 points
In this article, we would like to show you onwheel
event example in JavaScript.
Quick solution:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.addEventListener('wheel', function() {
4
console.log('onwheel event occurred.');
5
});
or:
xxxxxxxxxx
1
<div onwheel="handleWheel()"> div body here... </div>
or:
xxxxxxxxxx
1
var myElement = document.querySelector('#my-element');
2
3
myElement.onwheel= function() {
4
console.log('onwheel event occurred.');
5
};
There are three common ways how to use onwheel
event:
- with event listener,
- with element attribute,
- with element property.
In this section, we want to show how to use onwheel
event on div
element via event listener mechanism.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
body {
6
height: 100px;
7
}
8
#my-div {
9
overflow: scroll;
10
height: 300px;
11
background: lightgray;
12
}
13
</style>
14
</head>
15
<body>
16
<div id="my-div">Scroll the div element.</div>
17
<script>
18
var myDiv = document.querySelector('#my-div');
19
myDiv.addEventListener("wheel", handleWheel);
20
21
function handleWheel(){
22
console.log('onwheel event occurred.');
23
}
24
</script>
25
</body>
26
</html>
In this section, we want to show how to use onwheel
event on div
element via attribute.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
body {
6
height: 100px;
7
}
8
div {
9
overflow: scroll;
10
height: 300px;
11
background: lightgray;
12
}
13
</style>
14
</head>
15
<body>
16
<div onwheel="handleWheel()">Scroll the div element.</div>
17
<script>
18
function handleWheel(){
19
console.log('onwheel event occurred.');
20
}
21
</script>
22
</body>
23
</html>
In this section, we want to show how to use onwheel
event on div
element via property.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
body {
6
height: 100px;
7
}
8
#my-div {
9
overflow: scroll;
10
height: 300px;
11
background: lightgray;
12
}
13
</style>
14
</head>
15
<body>
16
<div id="my-div">Scroll the div element.</div>
17
<script>
18
var myDiv = document.querySelector("#my-div");
19
myDiv.onwheel = function (){
20
console.log('onwheel event occurred.');
21
}
22
</script>
23
</body>
24
</html>