Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Client-side paging with jQuery

4.47/5 (7 votes)
25 Jul 2011CPOL3 min read 79.6K  
A mash-up of sorts built using Microsoft's jQuery Template plugin along with G Birke's jQuery Pagination plugin & a photo-stream from Flickr acting as a data source

Introduction

jQuery has simplified web development by providing alternative ways to perform tasks that were done with server-side code, and that too with a lot lesser code. Paging allows you to reduce the page size and render time of your site or web application by breaking up large data sets into discrete pages. Paging a result-set typically requires a postback for fetching a new batch. With Gabriel Birke's jQuery Pagination plugin, you can get all the records from a data source at once if they are small in number and show them one bunch at a time or fetch a specified set of records one at a time while getting subsequent records through AJAX on further clicks of the pagination elements.

To illustrate client-side paging of dynamically generated records, I built a mash-up of sorts using Microsoft's jQuery Template plugin (minified version: ~6KB) alongwith G Birke's jQuery Pagination plugin (minified version: ~3KB) and a photo-stream from Flickr as a data source. I've shared my code sample on JSBin where you can see the source as well as the output.

Background

This sample is an adaptation of Stephen Walther's Templates plugin example and a Pagination plugin example by StackOverflow.com member brianpeiris with additional help from the StackOverflow Forum.

Using the Code

The explanation follows after the code listing:

HTML
<html>
<head>

    <script type="text/javascript" 
	src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

    <script type="text/javascript" 
	src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js">
    </script>

    <script type="text/javascript" src="js/jquery.pagination.js"></script>

    <title>Client-side Paging with jQuery</title>
    <style type="text/css" media="screen">
        body
        {
            background-color: #000;
            font: 16px Helvetica, Arial;
            color: #fff;
        }
        .pagination
        {
            font-size: 80%;
        }
        .pagination a
        {
            text-decoration: none;
            border: solid 1px #AAE;
            color: #15B;
        }
        .pagination a, .pagination span
        {
            display: block;
            float: left;
            padding: 0.3em 0.5em;
            margin-right: 5px;
            margin-bottom: 5px;
        }
        .pagination .current
        {
            background: #26B;
            color: #fff;
            border: solid 1px #AAE;
        }
        .pagination .current.prev, .pagination .current.next
        {
            color: #999;
            border-color: #999;
            background: #fff;
        }
    </style>

    <script>
    var pagination_options = {
      num_edge_entries: 2,
      num_display_entries: 8,
      callback: pageselectCallback,
      items_per_page:3
    }

    function pageselectCallback(page_index, jq){
      var items_per_page = pagination_options.items_per_page;
      var offset = page_index * items_per_page;
      var new_content = $('#hiddenresult div.result').slice
			(offset, offset + items_per_page).clone();
      $('#searchresult').empty().append(new_content);
      return false;
    }

    function initPagination() {
      var num_entries = $('#hiddenresult div.result').length;
      // Create pagination element
      $("#pagination").pagination(num_entries, pagination_options);
    }
  
     $(document).ready(function(){   
    var url = "http://api.flickr.com/services/feeds/groups_pool.gne?
		id=44124373027@N01andlang=en-usandformat=jsonandjsoncallback=?";
 
        // Grab some flickr images of cats
        $.getJSON(url, function (data) {
            // Format the data using the catTemplate template
            $("#catTemplate").tmpl(data.items).appendTo("#hiddenresult");
            initPagination();
	    //
		  $("#fetching").hide();
        });
    });
    </script>

</head>
<body>
    <p id="fetching">
        Fetching cat photos from Flickr...
    </p>
    <div id="pagination" class="pagination">
    </div>
    <br style="clear: both;" />
    <div id="searchresult">
    </div>
    <div id="hiddenresult" style="display: none;">
    </div>

    <script id="catTemplate" type="text/x-jquery-tmpl">
        <div class="result">
    <p>
            <b>${title}</b>
            <br />
            <img src="${media.m}" />
        </p>
    </div>
    </script>

</body>
</html>

Let's walk through the code...

The sample requires three external JavaScript files - the jQuery library, the jQuery Template plugin and the jQuery Pagination plugin which you have to get from Github.

The Pagination plugin generates links for paging based on the items per page (items_per_page) that you specify. The plugin is highly configurable through the option parameter (pagination_options) and all Pagination elements can be styled separately.

As the page loads, a JSON feed of cat photos from Flickr is fetched. The records from the JSON feed go into the mould created by the Template plugin and the title and the image URL of each photo are extracted from the feed. There are 2 DIV placeholders that have the IDs "hiddenresult" and "searchresult". All the formatted records go into "hiddenresult" DIV but they are not shown.

The initPagination then gets into action. It calculates the number of records and provides that as an input to the all powerful pagination method which fills the "pagination" DIV container with hyperlinks to provide page navigation. The pageselectCallback function aids it in splicing the entire resultset from "hiddenresult" DIV and stuffing chunks of pre-determined size into the "searchresult" DIV.

The above technique of getting all the records at once and showing them as smaller chunks is suitable when the resultset is small.

The capabilities of the jQuery Template are hardly used in this sample as the idea is to show the power of these 2 plugins in their most basic form. If the resultset contained some serious data and some of it had to be shown conditionally, the jQuery Template plugin has tags that can act on the data and manipulate it as required.

Points of Interest

Some things to keep in mind while working with jQuery plugins:

  • Note which version of a jQuery plugin you are using and if it needs a specific version of the jQuery library and any other dependent files.
  • Pick Plugins which have good documentation and demos. If you pick a popular one, the chances of getting quick help from online forums will be higher.
  • Find out if the license policy for that Plugin suits your needs. Plugins hosted on Github generally have liberal licensing.
  • Access the jQuery library from Google's or Microsoft's CDN for decreased latency, increased parallelism, and better caching.

I'm amazed at the sheer number of jQuery plugins that developers worldwide painstakingly build and voluntarily share. There is a vibrant, responsive jQuery community online that offers feedback and support to those seeking it. This community is one big reason that makes jQuery special when compared to other JavaScript libraries. So the next time you get some special requirements for a custom web app, see if there is already a jQuery plugin that can do the job.

History

  • Created: 25-July-2011

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)