Infinite Scroll for Mike
by sberube
HTML
<div style="height: 100%">
<div id="container"></div>
<div id="status"></div>
</div>
CSS
body, html {
height: 100%;
}
#container {
border: 1px solid black;
overflow: auto;
height: 80%;
width: 500px;
}
JavaScript
var initialCount = 30;
var loadMoreCount = 30;
var index = 0;
var isLoading = false;
/* Event Handlers */
$("#container").on("scroll", function (event) {
$("#status").text('Scrolled');
handleScrollChange();
});
$(window).on("resize", function (event) {
$("#status").text('Resized');
handleScrollChange();
});
/* Get Data method */
var loadMore = function (count) {
isLoading = true;
for (var i = index; i < count + index; i++) {
$("#container").append("<div><label>Entry " + i + "</label></div>");
}
index = index + count;
isLoading = false;
};
/* Scroll Handler */
var lastScrollPosition = 0;
var getScrollInfo = function() {
var el = $("#container")[0];
return {
height: el.offsetHeight,
scrollHeight: el.scrollHeight,
scrollTop: el.scrollTop
}
}
var handleScrollChange = function () {
var si = getScrollInfo();
// CHECK - if user is scrolling up = DO nothing!
if (lastScrollPosition > si.scrollTop) {
return;
} else {
lastScrollPosition = si.scrollTop;
}
if (!isLoading && si.scrollTop + si.height >= si.scrollHeight - 150) {
loadMore(loadMoreCount);
}
};
/* End Scroll Handler */
// Loading initial data set.
loadMore(initialCount);