Scroll on div is not fired

Viewed 34

I have this code :

const listElm = document.querySelector('#infinite-list');
  listElm.addEventListener('scroll', e => {
    if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
      this.loadMore();
    }
  });

The event is not fired, even if the div infinite-list contains enough html data to display; Any ides ? Btw is fired with wheel but I need to fired when scroll;

1 Answers

Don't use scroll listener for stuff like this, use Intersection Observer (IO) for this. With this you can observe an element and react whenever it intersects with either another element or the viewport.

You can observe an empty element at the end of your list and whenever it comes into view, load more items.

let options = {
  rootMargin: '0px',
  threshold: 1.0
}

callback = (entries, observer) => {
 console.log(entries, observer);
 if (entries[0].isIntersecting) {
   loadMoreItems();
 }
}

// this is just mocking adding more items, you can ignore this function. 
loadMoreItems = () => {
  let newItems = 10;
  const list = document.getElementById('list');
  while (newItems--) { // do this until we reach 0, which is "false"
    const item = document.createElement('li');
    item.append('Some random text: ' + Math.floor( Math.random() * 7 ));
    list.appendChild(item);
  }
}

let observer = new IntersectionObserver(callback, options);
observer.observe(document.getElementById('observedEl'));
li {min-height: 20vh;}

li:nth-child(2n) {
  background-color: #a2a2a2;
}
<ul id="list">
 <li> Item </li>
 <li> Item </li>
 <li> xxx </li>
 <li> ASDF </li>
 <li> Whatever </li>
 <li> One more </li>
</ul>
<div id="observedEl"></div>

Related