Simple jQuery Script For Table Pagination On Browser

File Size: 2.25 KB
Views Total: 3193
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Simple jQuery Script For Table Pagination On Browser

Table Pagination is a simple jQuery script that adds client-side pagination capability to your existing long table without any much effort on server side.

How to use it:

1. Load the needed jQuery JavaScript library in your webpage.

<script src="//code.jquery.com/jquery.min.js"></script>

2. Add pagination links (next/prev buttons) to your html table.

<span class="prev">
  <<< Previous
</span> 

<span class="next">
  Next >>>
</span>

3. Specify the number of table rows to be displayed per page.

var maxRows = 5;

4. The core JavaScript for the table pagination.

$('table').each(function() {
  var cTable = $(this);
  var cRows = cTable.find('tr:gt(0)');
  var cRowCount = cRows.size();
  
  if (cRowCount < maxRows) {
      return;
  }

  cRows.each(function(i) {
      $(this).find('td:first').text(function(j, val) {
         return (i + 1) + " - " + val;
      }); 
  });

  cRows.filter(':gt(' + (maxRows - 1) + ')').hide();


  var cPrev = cTable.siblings('.prev');
  var cNext = cTable.siblings('.next');

  cPrev.addClass('disabled');

  cPrev.click(function() {
      var cFirstVisible = cRows.index(cRows.filter(':visible'));
      
      if (cPrev.hasClass('disabled')) {
          return false;
      }
      
      cRows.hide();
      if (cFirstVisible - maxRows - 1 > 0) {
          cRows.filter(':lt(' + cFirstVisible + '):gt(' + (cFirstVisible - maxRows - 1) + ')').show();
      } else {
          cRows.filter(':lt(' + cFirstVisible + ')').show();
      }

      if (cFirstVisible - maxRows <= 0) {
          cPrev.addClass('disabled');
      }
      
      cNext.removeClass('disabled');

      return false;
  });

  cNext.click(function() {
      var cFirstVisible = cRows.index(cRows.filter(':visible'));
      
      if (cNext.hasClass('disabled')) {
          return false;
      }
      
      cRows.hide();
      cRows.filter(':lt(' + (cFirstVisible +2 * maxRows) + '):gt(' + (cFirstVisible + maxRows - 1) + ')').show();

      if (cFirstVisible + 2 * maxRows >= cRows.size()) {
          cNext.addClass('disabled');
      }
      
      cPrev.removeClass('disabled');

      return false;
  });

});

This awesome jQuery plugin is developed by Thedijje. For more Advanced Usages, please check the demo page or visit the official website.