Skip to content

Instantly share code, notes, and snippets.

@hartliddell
Forked from ChrisLTD/InfiniteScroll-ES6.js
Created May 7, 2016 20:52
Show Gist options
  • Save hartliddell/5a7e0ffa874840360ddb7bd43de5edae to your computer and use it in GitHub Desktop.
Save hartliddell/5a7e0ffa874840360ddb7bd43de5edae to your computer and use it in GitHub Desktop.
Infinite "Scroll" javascript module for ES6
'use strict';
// Infinite scrolling loader, fires off a button click
//
// Sample HTML:
// <div id="infinite-scroll" 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 infiniteScrollAreaId= 'infinite-scroll';
class InfiniteScroll {
constructor(el) {
this.el = el;
this.bindNextButton();
this.spinnerEl = document.querySelector(spinnerSelector);
}
bindNextButton = () => {
var nextButtonsEl = document.querySelector(nextButtonSelector);
nextButtonsEl.addEventListener('click', this.loadNext);
};
showSpinner = () => {
this.spinnerEl.style.display = 'block';
};
hideSpinner = () => {
this.spinnerEl.style.display = 'none';
};
loadNext = (e) => {
const url = e.target.href;
const button = e.target;
e.preventDefault();
button.parentNode.removeChild(button);
this.showSpinner();
this.requestNextHtml(url);
};
requestNextHtml = (url) => {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
// Success!
var 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) => {
var tempDoc = document.implementation.createHTMLDocument();
tempDoc.body.innerHTML = htmlString;
return tempDoc.getElementById(infiniteScrollAreaId);
};
appendNewPosts = (postsHTML) => {
this.el.appendChild(postsHTML);
this.hideSpinner();
this.bindNextButton(); // bind new pagination button
};
}
export default InfiniteScroll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment