EN
JavaScript - wheel event example
0
points
In this article, we would like to show you onwheel
event example in JavaScript.
Quick solution:
var myElement = document.querySelector('#my-element');
myElement.addEventListener('wheel', function() {
console.log('onwheel event occurred.');
});
or:
<div onwheel="handleWheel()"> div body here... </div>
or:
var myElement = document.querySelector('#my-element');
myElement.onwheel= function() {
console.log('onwheel event occurred.');
};
Practical examples
There are three common ways how to use onwheel
event:
- with event listener,
- with element attribute,
- with element property.
1. Event listener based example
In this section, we want to show how to use onwheel
event on div
element via event listener mechanism.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 100px;
}
#my-div {
overflow: scroll;
height: 300px;
background: lightgray;
}
</style>
</head>
<body>
<div id="my-div">Scroll the div element.</div>
<script>
var myDiv = document.querySelector('#my-div');
myDiv.addEventListener("wheel", handleWheel);
function handleWheel(){
console.log('onwheel event occurred.');
}
</script>
</body>
</html>
2. Attribute based example
In this section, we want to show how to use onwheel
event on div
element via attribute.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 100px;
}
div {
overflow: scroll;
height: 300px;
background: lightgray;
}
</style>
</head>
<body>
<div onwheel="handleWheel()">Scroll the div element.</div>
<script>
function handleWheel(){
console.log('onwheel event occurred.');
}
</script>
</body>
</html>
3. Property based example
In this section, we want to show how to use onwheel
event on div
element via property.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 100px;
}
#my-div {
overflow: scroll;
height: 300px;
background: lightgray;
}
</style>
</head>
<body>
<div id="my-div">Scroll the div element.</div>
<script>
var myDiv = document.querySelector("#my-div");
myDiv.onwheel = function (){
console.log('onwheel event occurred.');
}
</script>
</body>
</html>