JSFiddle - React, Tailwind, and code Playground
by nathanlogan
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="container"></div>
<div id="log">Scroll down...<br /></div>
CSS
#container {min-height:4000px; border:5px solid purple; padding:10px; margin:15px 10px; background: linear-gradient(to bottom, #f8ffe8 0%,#e3f5ab 33%,#b7df2d 100%);}
#log {
display:inline-block;
padding:10px;
position:fixed;
bottom:10px;
right:35px;
border:2px solid #666;
background:#eee;
}
JavaScript
// parameter: number of results to return on each AJAX call
var numberOfResults = 30;
// number of milliseconds to wait between scroll events
var throttleDuration = 200;
// # of px from the bottom at which point we should go get another round of items
var pxScrollOffset = 300;
// state variable: tracks all results
var allResults = [];
// total possible results for this view
var totalResults = undefined;
// temp state var to track AJAX call being out
var ajaxInTransit = false;
// AJAX call to get all results
var getTotalResults = function() {
// this is where you'd do your AJAX call
// faking our AJAX call
totalResults = 40;
}
// AJAX request more results
// once those results are returned, append to the collection
var getMoreResults = function() {
// check that we aren't already at max results
if (allResults.length < totalResults) {
// check that the AJAX call isn't already in progress
if (!ajaxInTransit) {
ajaxInTransit = true;
// fake the AJAX delay!
setTimeout(function(){
var num = allResults.length;
// append results to collection
allResults.push(num+1, num+2, num+3, num+4, num+5, num+6, num+7, num+8, num+9, num+10);
// update view
updateView();
ajaxInTransit = false;
}, 2000);
}
}
}
var updateView = function(){
var compiled = _.template('<% _.forEach(ideas, function(idea) { %><li><%- idea %></li><% }); %>');
$('#container').html( compiled({ 'ideas': allResults }) );
}
// listen for the user to get sufficiently close to the bottom of the list & calls getMoreResults()
var listenForBottomScroll = function() {
var scrollEventCounter = 0;
$(window).scroll(_.throttle(function(e) {
// we reached the bottom (less the offset defined above)
if ($(window).scrollTop() + $(window).height() >= (getDocHeight()-pxScrollOffset)) {
...