Automatic Pagination: The Infinite List using iUI and jQuery

by Michael

Automatic pagination means that we progressively load in new data without the user having to actively click on a page link. This way, we can create lists that seem infinitely long since we automatically load the next page when the user is about to scroll to the end of the list.

The implementation is quite simple. We create an initial page that contains all the mark-up required to qualify as an HTML web page. In this page, we have an unordered list.

<ul>
    <li>an item</li>
    <li>another item</li>
    <li><a href="/get/more/items?page=2" target="_replace">Get more items</a></li>
</ul>

Note that the last item is an anchor which contains a URL with a pagination parameter. The page that it links to looks like the following piece of mark-up.

<li>even more items</li>
<li>list are great</li>
<li>itemized</li>
<li><a href="/get/more/items?page=3" target="_replace">Get more items</a></li>

Normally iUI would load the content when the user clicks on the link. But to automate the process, we can add a few lines of JavaScript to our web app.

/*** JS Code using iUI framework and jQuery ***/

var ns = {};

// Throttle the requests (in this case 1 second)
ns.throttle = 1000;
ns.isOkToLoad = true;

// Number of pixels before last element
ns.scrollPadding = 100;

(function() {
    ns.autoloadOnScroll = function(event) {
        if (!ns.isOkToLoad)
            return;

        var scrlHeight = window.document.body.scrollHeight;
        var scrlPos = window.innerHeight + window.scrollY;

        if (scrlHeight < (ns.scrollPadding + scrlPos)) {
            var link = $("a[target=_replace]").get(0);
            if (link) {
                setTimeout("ns.isOkToLoad = true", ns.throttle);
                ns.isOkToLoad = false;
                iui.showPageByHref(link.href,
                                   null,
                                   null,
                                   link,
                                   iui.unselect);
            }
        }
    };
})();

$(function() {
    window.onscroll = ns.autoloadOnScroll;
});

You could set ns.isOkToLoad = true in the callback from the XHR (which is done inside iui.showPageByHref).

Links

Advertisements