JSFiddle - React, Tailwind, and code Playground

by ashish shubham

HTML

<div class="container">

</div>

CSS

.container {
  height: 300px;
  width: 80%;
  border: 1px solid black;
  overflow: auto;
}

.item {
  display: inline-block;
  width: 50px;
  height: 50px;
  background-color: #d1d3d8;
  margin: 10px;
}

JavaScript

function getContent(offset, num) {
  // Do not change this method.
	const content = [];
  for( i=0; i<num; i++) {
  	content.push(offset + i);
  };
  return new Promise((resolve, reject) => {
  	setTimeout(() => {
    	resolve(content);
    }, Math.random() * 2000);
  })
}

class InfiniteScroll {
  constructor(config) {
    this.offset = config.offset;
    this.num = config.num;
    this.scrollThreshold = config.scrollThreshold;
    this.container = config.container;
    this.getContent = config.getContent;
    this._bindEventListeners();
    this.getContent(this.offset, this.num).then(content => { this.insertContent.bind(this, content);
    this.offset +=this.num;
    });
    
  }
  
  _bindEventListeners() {
    this.container && this.container.addEventListener('scroll', this.handleScroll.bind(this));
  }
  
  handleScroll() {
    if (this.container.scrollHeight - this.container.scrollTop - 300 <   this.scrollThreshold) {
      this.getContent(this.offset, this.num).then(content => {
      this.insertContent.bind(this, content);
      this.offset += this.num;
    });
  }
  }
  
  insertContent(content) {
    content.forEach(c => {
    let el = document.createElement('div');
    el.innerHTML = c;
    el.setAttribute('class', 'item');
    this.container.appendChild(el);
    });
  }
}

let infiniteScroll = new InfiniteScroll({
  container: document.querySelector('.container'),
  getContent: getContent,
  scrollThreshold: 100,
  offset: 0,
  num: 50
});