Last active
January 6, 2020 18:00
-
-
Save ChrisLTD/14efd71b32aed66ae66754d699807a25 to your computer and use it in GitHub Desktop.
Infinite "Scroll" javascript module for ES6
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
'use strict'; | |
// Infinite scrolling loader, fires off a button click | |
// | |
// Sample HTML: | |
// <div class="js-infinite-scroll"> | |
// POSTS HERE | |
// <a href="/url-to-more-content" class="js-infinite-scroll-next-button">Load More</a> | |
// </div> | |
// <div class="js-infinite-scroll-loading">...</div> | |
// | |
// Initialization: | |
// new InfiniteScroll( document.querySelector('.js-infinite-scroll') ); | |
const nextButtonSelector = '.js-infinite-scroll-next-button'; | |
const spinnerSelector = '.js-infinite-scroll-loading'; | |
const infiniteScrollAreaSelector = '.js-infinite-scroll'; | |
class InfiniteScroll { | |
constructor(el) { | |
this.el = el; | |
this.bindNextButton(); | |
this.spinnerEl = document.querySelector(spinnerSelector); | |
} | |
bindNextButton = () => { | |
const nextButtonsEl = document.querySelector(nextButtonSelector); | |
nextButtonsEl.addEventListener('click', this.loadNext); | |
}; | |
showSpinner = () => { | |
this.spinnerEl.style.display = 'block'; | |
}; | |
hideSpinner = () => { | |
this.spinnerEl.style.display = 'none'; | |
}; | |
loadNext = (e) => { | |
e.preventDefault(); | |
const url = e.target.href; | |
const button = e.target; | |
button.parentNode.removeChild(button); | |
this.showSpinner(); | |
this.requestNextHtml(url); | |
}; | |
requestNextHtml = (url) => { | |
const request = new XMLHttpRequest(); | |
request.open('GET', url, true); | |
request.onload = () => { | |
if (request.status >= 200 && request.status < 400) { | |
// Success! | |
const responseString = request.responseText; | |
const newPosts = this.getPostsFromHTML(responseString); | |
this.appendNewPosts(newPosts); | |
} | |
else { | |
console.log("We reached our target server, but it returned an error"); | |
this.hideSpinner(); | |
} | |
}; | |
request.onerror = function() { | |
console.log("There was a connection error of some sort"); | |
this.hideSpinner(); | |
}; | |
request.send(); | |
}; | |
getPostsFromHTML = (htmlString) => { | |
const tempDoc = document.implementation.createHTMLDocument(); | |
tempDoc.body.innerHTML = htmlString; | |
return tempDoc.querySelector(infiniteScrollAreaSelector); | |
}; | |
appendNewPosts = (postsHTML) => { | |
this.el.appendChild(postsHTML); | |
this.hideSpinner(); | |
// bind new pagination button if one came along with the postsHTML | |
this.bindNextButton(); | |
}; | |
} | |
export default InfiniteScroll; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment