EN
JavaScript - scroll stop event
12
points
In this short article we would like to show how to detect scroll stop event (scroll end event).
Some web browser introduced in 2023 scrollend
event, so still there is needed some legacy solution.
Quick solution:
element.addEventListener('scrollend', (event) => {
// ...
});
Note: we can use
element.onscrollend = (event) => { /* ... */ };
construction also.
Legacy solution
Legacy solution for the problem is to use some trick: do some logic when scroll event doesn't occur few milliseconds after appeared.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body style="height: 200px;">
<div style="background: silver; height: 600px;">
Scroll me up, down, up down and stop!
</div>
<script>
// Reusable function:
function createScrollStopListener(element, callback, timeout) {
if (timeout == null) {
timeout = 200; // default 200 ms
}
var removed = false;
var handle = null;
var handleScroll = function() {
if (handle) {
clearTimeout(handle);
}
handle = setTimeout(callback, timeout);
};
element.addEventListener('scroll', handleScroll);
return function() {
if (removed) {
return;
}
element.removeEventListener('scroll', handleScroll);
if (handle) {
clearTimeout(handle);
}
removed = true;
};
}
// Example usage:
createScrollStopListener(window, function() { // <div> elements based example is in the next section
console.log('window: onscrollstop');
});
</script>
</body>
</html>
Another example
In this section, you can find scroll stop event that is connected to div
elements.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
body {
height: 210px;
}
div.container {
background: silver;
height: 100px;
overflow-y: scroll;
}
div.content {
background: gold;
height: 1000px;
}
</style>
<script>
// Reusable function:
function createScrollStopListener(element, callback, timeout) {
if (timeout == null) {
timeout = 200; // default 200 ms
}
var removed = false;
var handle = null;
var handleScroll = function() {
if (handle) {
clearTimeout(handle);
}
handle = setTimeout(callback, timeout);
};
element.addEventListener('scroll', handleScroll);
return function() {
if (removed) {
return;
}
element.removeEventListener('scroll', handleScroll);
if (handle) {
clearTimeout(handle);
}
removed = true;
};
}
</script>
</head>
<body>
<div id="container-1" class="container">
<div class="content">Scroll me up, down, up down and stop!</div>
</div>
<br />
<div id="container-2" class="container">
<div class="content">Scroll me up, down, up down and stop!</div>
</div>
<script>
// Example usage:
var container1 = document.querySelector('#container-1');
var container2 = document.querySelector('#container-2');
createScrollStopListener(container1, function() {
console.log('container-1 element: onscrollstop');
});
createScrollStopListener(container2, function() {
console.log('container-2 element: onscrollstop');
});
</script>
</body>
</html>