jQuery: easy table pagination

jQuery: easy table pagination

How to easily paginate tables with jQuery.

I'm currently working on a project which involves a massive use of tables to display database data. Basically, you have two feasible options: either you choose to paginate tables on the server-side or to display a pagination system using jQuery. In this article we'll cover the latter option.

From a pure DOM perspective, a table is made of rows. With jQuery, you can slice these rows and hide each group. Then, when a user clicks on a pagination button, you simply display the current row group.

This solution implies a proper handling of the table structure. In other words, you should always specify a tbody element on each table. Browsers always add this element under the hood, but this is actually a recommended best practice which also enhances accessibility.

Our solution is as follows:

$('table.paginated').each(function() {
    var currentPage = 0;
    var numPerPage = 10;
    var $table = $(this);
    $table.bind('repaginate', function() {
        $table.find('tbody tr').hide().slice(currentPage * numPerPage, (currentPage + 1) * numPerPage).show();
    });
    $table.trigger('repaginate');
    var numRows = $table.find('tbody tr').length;
    var numPages = Math.ceil(numRows / numPerPage);
    var $pager = $('<div class="pager"></div>');
    for (var page = 0; page < numPages; page++) {
        $('<span class="page-number"></span>').text(page + 1).bind('click', {
            newPage: page
        }, function(event) {
            currentPage = event.data['newPage'];
            $table.trigger('repaginate');
            $(this).addClass('active').siblings().removeClass('active');
        }).appendTo($pager).addClass('clickable');
    }
    $pager.insertBefore($table).find('span.page-number:first').addClass('active');
});

We start with defining the number of rows to be displayed on each page (10). Then we create a custom event on the table (repaginate) which in its essence simply hides all rows and then displays only the current sliced group.

Next step is to get the total number of pages. Done that, we simply run a loop to create all the pagination buttons. We attach a click event on each button. We also use jQuery's event data to store the current page number. Each button will trigger the custom repaginate event.

You can see the demo below.

Demo

Live demo