Created
January 19, 2018 17:05
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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