How To Code a Sortable Table with jQuery


There is a small handful of free open source jQuery plugins to help organize special tables. More specifically these plugins offer unique & dynamic functionality such as pagination, row highlighting, and column sorting. The ability to sort your data is crucial when looking for patterns. It may also help you see the information from a different perspective altogether.
So for this tutorial I want to demonstrate a very simple plugin using an HTML table. Some plugins require you to create the table in JSON, but it is often easier to work with something that can tie into HTML on the page. I’ll be using the jQuery Tablesorter plugin which is free to download and use on any number of projects. Take a peek at my live sample demo below.
demo tutorial tablesorter plugin jquery howto screenshot

Page Structure

The first step is to download a copy of the Tablesorter plugin along with a local copy of jQuery. Now tablesorter is hosted on Github but you can also find a download link right within the plugin webpage. All you need to include is the jquery.tablesorter.min.js file which should be copied into the same place as jQuery.
<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Simple Table Sorting with jQuery - Treehouse Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://d15dxvojnvxp1x.cloudfront.net/assets/favicon.ico">
  <link rel="icon" href="http://d15dxvojnvxp1x.cloudfront.net/assets/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/jquery.tablesorter.min.js"></script>
</head>
The downloaded source files also include sample demos and default CSS. If you don’t want to build your own design then feel free to copy over the CSS as well. Tablesorter was written to be simple and linear without too many requirements. I feel the stylesheets are well worth using if you are unsure of where to get started in regards to table design.
If you are not super comfortable with HTML table structure then this is the perfect time to familiarize yourself with the material. Each table requires a <thead> and <tbody> which separates the column headings from the content rows. Most web developers know that <tr>and <td> are used to encapsulate table rows and table data, respectively. But in the header we replace data tags with <th> for table headings.
  <table id="keywords" cellspacing="0" cellpadding="0">
    <thead>
      <tr>
        <th><span>Keywords</span></th>
        <th><span>Impressions</span></th>
        <th><span>Clicks</span></th>
        <th><span>CTR</span></th>
        <th><span>Rank</span></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="lalign">silly tshirts</td>
        <td>6,000</td>
        <td>110</td>
        <td>1.8%</td>
        <td>22.2</td>
      </tr>
This is very important because many other table plugins will require the same page structure. And even if you weren’t using a plugin, it is good to understand semantics for your next project which requires tabular data.
Note I haven’t included a full copy of the table because it is mostly repetition. Adding your own data into the HTML will probably be the most time-intensive part of this whole process, mostly because you will likely need to organize all your data first. There are some basic tools online for auto-generating HTML code but it’s a much better idea to write it all yourself.

Custom CSS Styles

I want to jump into my own styles.css file which is the only stylesheet used in this demo. I typically include a simple CSS reset based off Eric Meyer’s template. Also at the top of the document I have an import rule to include an external Google Web Font for the heading text.
However the most important customizations are found towards the bottom of the file. I labeled this inner table with an ID of #keywords because the demo is sorting through fictional search engine keyword results. Aside from the typical HTML elements you will also find classes appended onto specific columns which makes styling a whole lot easier.
#keywords {
  margin: 0 auto;
  font-size: 1.2em;
  margin-bottom: 15px;
}


#keywords thead {
  cursor: pointer;
  background: #c9dff0;
}
#keywords thead tr th { 
  font-weight: bold;
  padding: 12px 30px;
  padding-left: 42px;
}
#keywords thead tr th span { 
  padding-right: 20px;
  background-repeat: no-repeat;
  background-position: 100% 100%;
}

#keywords thead tr th.headerSortUp, #keywords thead tr th.headerSortDown {
  background: #acc8dd;
}

#keywords thead tr th.headerSortUp span {
  background-image: url('up-arrow.png');
}
#keywords thead tr th.headerSortDown span {
  background-image: url('down-arrow.png');
}


#keywords tbody tr { 
  color: #555;
}
#keywords tbody tr td {
  text-align: center;
  padding: 15px 10px;
}
#keywords tbody tr td.lalign {
  text-align: left;
}
To be more specific, I’ve wrapped the text of each table header inside a span tag. This isn’t necessary to include sorting arrows but I found it to be the easiest approach. Basically when clicking any table header a new class is appended onto the <th> element. Every inner span element gets a non-repeatable background image displayed over to the right side of the text.
However the image itself will depend on which class has been added. If there is no class then we don’t use any image and the space just appears empty. Headings with a class.headerSortUp displays an up arrow, representing ascending order. In the opposite case we switch the arrow icon for .headerSortDown.
I want to point out that you can really go crazy with these classes by updating borders, background colors, etc. I wanted to use this demo as a showcase of what is possible. With some knowledge of advanced CSS properties you can really manipulate the selected table column to appear in many different styles.

Sorting with jQuery

Since my demo includes a small number of rows I’ve setup the plugin using the smallest amount of code possible. Simply put, Tablesorter is amazing for any project where you need to dynamically sort information. There are no required options but many are available if you wish to try them out (see the online documentation).
$(function(){
  $('#keywords').tablesorter(); 
});
My jQuery selector targets the keywords table and then runs tablesorter(). This will make each heading clickable and thus able to sort through your data. It is amazing how this plugin will recognize various types of data like strings, floating numbers, even symbolic numbers like currency or percentages.
I want to provide one more sample bit of code in relation to paginating your data. You can find a live sample on the plugin webpage to see how this looks in a real-world example. Also remember that everything is designed using CSS and it’s very simple to customize this yourself.
$(document).ready(function() { 
    $("table").tablesorter({widthFixed: true, widgets: ['zebra']}).tablesorterPager({container: $("#pager")}); 
}); 
In order for this to work you need to download the plugin extension and include this along with the other JS scripts, because the pagination is not built into the core plugin functionality. There are some other related add-on scripts and themes you may try out at your own accord.
In that sample code above you will also notice some regular options passed into the Tablesorter function. The first pieces you’ll notice are default config options which are outlined in the documentation. Zebra striping is an extended widget – check out more about these widgets from this sample demo page. It is possible for developers to even write their own widgets and thus extend more functionality out of this plugin.

Final Thoughts

Although Tablesorter is quite easy to set up, the custom options allow for a much greater user experience. Even the small pagination demo can be helpful if you are including many rows of data. While Tablesorter is very basic and will require extra CSS to get the page looking sharp, it’s my opinion that it is well worth the effort, because of all the extra functionality you can gain by working with jQuery. Feel free to download a sample copy of my demo and see how you can implement table sorting into your own web projects

Comments

Popular posts from this blog

Bootstrap Tags Input

Eloqent Usage