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'
});
This will start an infinite rAF loop if the scrolling is discarded by an other scroll, or if it didn't produce anything (e.g scrollTo(currentPosition))
And works in a single direction
@Kaiido It Just does what OP asked, It doesn't take into account any context
It doesn't "detect when scroll ended" no, it does "detect when the scrolltop is bigger than the target position" which says nothing about the scroll action, and will fail in the cases I exposed in my previous comments, that OP never said it's ok to ignore.