Skip to content

Instantly share code, notes, and snippets.

@Pamblam
Created January 19, 2018 17:05
Show Gist options
  • Select an option

  • Save Pamblam/fed48a373b5dfe7516638479e909748a to your computer and use it in GitHub Desktop.

Select an option

Save Pamblam/fed48a373b5dfe7516638479e909748a to your computer and use it in GitHub Desktop.
This is a class that adds items to the top of an element when it's scrolled up, starting the element at the very bottom. See: https://stackoverflow.com/a/48346059/1444609
class upScroller{
constructor(ele = document.body){
this.renderedItems = 0;
this.ele = ele; var i=0;
this.initBoxContents();
}
initBoxContents(){
if(this.ele.scrollHeight == this.ele.clientHeight)
this.populateNextItem().then(()=>this.initBoxContents());
else{
this.ele.scrollTop = this.ele.clientHeight;
this.attachScrollListener();
}
}
getNextItem(){
// Do something here to get the next item to render
// preferably using ajax but I'm using setTimeout
// to emulate the ajax call.
return new Promise(done=>setTimeout(()=>{
this.renderedItems++;
done(`<p>This is paragraph #${this.renderedItems}</p>`);
},50));
}
populateNextItem(){
return new Promise(done=>{
this.getNextItem().then(item=>{
this.ele.insertAdjacentHTML('afterbegin', item);
done();
});
});
}
attachScrollListener(){
this.ele.addEventListener('scroll', ()=>{
if(this.ele.scrollTop) return;
var sh = this.ele.scrollHeight;
this.populateNextItem().then(()=>{
this.ele.scrollTop = this.ele.scrollHeight - sh;
});
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment