I want to add a class to selected element after scroll ended. How can I detect scroll ended in JS?
HTML
<ul class="list" id="wrapper">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li id="element">7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
JS
const element = document.getElementById('element');
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
You could use requestAnimationFrame
to detect when the scrollTop
is greater than y
requestAnimationFrame
is way better than setting both an interval and an event listener on scroll, for a matter of performance.
const element = document.getElementById('element');
const y = element.getBoundingClientRect().top + window.scrollY;
function checkScrollEnd() {
if ((window.scrollY || document.body.scrollTop || document.documentElement.scrollTop) < y) {
window.requestAnimationFrame(checkScrollEnd);
}
else {
alert('end of scroll')
}
}
window.requestAnimationFrame(checkScrollEnd);
window.scroll({
top: y,
behavior: 'smooth'
});