I wrote this function using the ideas of Hussein and Nick, but I wanted it to use promises for a callback. I also wanted the infinite scroll area to be on a fixed div, and not just on the window if the div was sent to the options object. Below is an example of this in my second link below. I suggest using a promise library like Q if you want to support older browsers. The cb method may or may not be a promise, and it will work independently.
Used like this:
HTML
<div id="feed"></div>
Js
var infScroll = infiniteScroll({ cb: function () { return doSomethingPossiblyAnAJAXPromise(); } });
If you want the feed to pause temporarily, you can return false in the cb method. Useful if you are at the end of the feed. It can be started again by calling the infinScroll method "setShouldLoad" and returning true and example to execute the code above.
infScroll.setShouldLoad(true);
Endless scroll function is
function infiniteScroll (options) { // these options can be overwritten by the sent in options var defaultOptions = { binder: $(window), // parent scrollable element loadSpot: 300, // feedContainer: $("#feed"), // container cb: function () { }, } options = $.extend(defaultOptions, options); options.shouldLoad = true; var returnedOptions = { setShouldLoad: function (bool) { options.shouldLoad = bool; if(bool) { scrollHandler(); } }, }; function scrollHandler () { var scrollTop = options.binder.scrollTop(); var height = options.binder[0].innerHeight || options.binder.height(); if (options.shouldLoad && scrollTop >= (options.binder[0].scrollHeight || $(document).height()) - height - options.loadSpot) { options.shouldLoad = false; if(typeof options.cb === "function") { new Promise(function (resolve) {resolve();}).then(function() { return options.cb(); }).then(function (isNotFinished) { if(typeof isNotFinished === "boolean") { options.shouldLoad = isNotFinished; } }); } } } options.binder.scroll(scrollHandler); scrollHandler(); return returnedOptions; }
1 example feed with a window as a scroller
2 example feed from a feed as a scroller
John Mar 26 '15 at 2:01 2015-03-26 02:01
source share