Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript scroll

How can I detect window scroll ended in javascript?

发布于 2020-03-27 15:41:58

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'
});

JSBIN EXAMPLE

Questioner
midstack
Viewed
19
Fabrizio Calderan 2020-01-31 17:20

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'  
});

Example fiddle