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:
<div id="my-element" onscroll="handleScroll()">
<!-- div body here... -->
</div>
or:
var myElement = document.querySelector('#my-element');
myElement.addEventListener('scroll', function() {
console.log('onscroll event occurred.');
});
or:
var myElement = document.querySelector('#my-element');
myElement.onscroll = function() {
console.log('onscroll event occurred.');
};
Note: it is very important to work on element that has scrollable content to handle
onscrollevent.
Practical examples
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.
1. Event listener based example
In this section, we want to show how to use scroll event on div element via event listener mechanism.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 100px;
}
div {
border: 1px solid black;
width: 150px;
height: 80px;
overflow: scroll;
}
</style>
</head>
<body>
<div id="my-element">
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
</div>
<script>
var myElement = document.querySelector('#my-element');
myElement.addEventListener('scroll', function() {
console.log('onscroll event occurred.');
});
</script>
</body>
</html>
2. Attribute based example
In this section we want to show how to use onscroll event on div element via attribute.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 100px;
}
div {
border: 1px solid black;
width: 150px;
height: 80px;
overflow: scroll;
}
</style>
</head>
<body>
<div onscroll="handleScroll()">
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
</div>
<script>
function handleScroll(){
console.log('onscroll event occurred.');
}
</script>
</body>
</html>
3. Property based example
In this section, we want to show how use onscroll event on div element via property.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 100px;
}
div {
border: 1px solid black;
width: 150px;
height: 80px;
overflow: scroll;
}
</style>
</head>
<body>
<div id="my-element">
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
Scroll the element.
</div>
<script>
var myElement = document.querySelector('#my-element');
myElement.onscroll = function() {
console.log('onscroll event occurred.');
};
</script>
</body>
</html>