LearnHow To Code a Sortable Table with jQuery

   
Avatar

Jake Rocheleau
writes on October 15, 2013

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

Live Demo Download the Source

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.

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

14 Responses to “How To Code a Sortable Table with jQuery”

  1. My programmer is trying to convince me to move to .net
    from PHP. I have always disliked the idea because of the expenses.

    But he’s tryiong none the less. I’ve been using WordPress on a number of websites
    for about a year and am worried about switching to another platform.
    I have heard good things about blogengine.net. Is there a way I can import all my
    wordpress content into it? Any kind of help would be really appreciated!

    • Good day. Over 80% of online applications and or dynamic websites use PHP at the the backend. Any developer who suggests .net, is probably very junior, with very little experience. Kids start out “programming” with Microsoft related wizards (.net etc) and then as they get more senior, slowly progresses to ultimately end up as a Java developer.

      I would say fire him, and get a more senior developer.

  2. I’m impressed… many plugins and tools claim simplicity in setup and run, but this one took less than 5 minutes to hook up and run and it worked. Can’t say much more than that.

  3. Is there a way to group rows visually (thru CSS) based on the value in the sort column?For example, if I have a table with the IP address per action, I might want to group all the actions from each client together. Simply sorting them in IP order means I have to read the entries, which is not as useful. So, perhaps, having the tableSorter code place a CSS tag (like firstRowInGroup or lastRowInGroup) on the first and last entry of each group of like-valued rows, post sorting, would enable simple CSS like:
    tr.lastRowInGroup { border-bottom: 1px solid black }
    [if your table is set to allow such row highlighting.]

  4. How can I use collaptable together with tablesort?

  5. スーパーコピー、スーパーコピーブランド(N級品)激安通販専門店世界一流ブランドコピー 財布、スーパーコピー 商品、激安ブランドコピー 。 ヴィトンコピー 、 ミョウミョウコピー 、シャネルコピー 、エル メスコピー 品格安通販。商品は全て最高な材料 と優れた技術で造られて、正規と比べて、品質が無差別です!人気ブランド..
    エルバーキンコピーエルメスバーキン30コピーエルメス ボリード47,エルメス バッグ 名前,エルメス ネクタイ ピンク エルメス クラッチバッグ,エルメス バッグ コピー,エルメス バーキン コピー エルメス 財布 ダミエ オークション,エルメス ヨーロッパ,エルメス エールライン エルメス クラッチ激安通販、高い品質、送料無料。バーキン25コピー、バーキン30コピー、バーキン35コピー、バーキン40コピーなど世界中有名なブランドレプリカを格安で通販しております。N級品スーパーコピーブランドは ブランドスーパーコピー超N品エルメスバッグ,エルメス バーキン25 , バーキン30.バーキン35.バーキン40. エルメス(HERMES) ケリー http://www.newkakaku.com/lz1.htm

  6. 秋冬物もかなりGOODです!最初はベストから。29081568のモンクレールダウンベストをおすすめ!
    スーパーコピー腕時計,ロレックスコピー,ブライトリングコピー,ボーム&メルシエコピー時計コピー業界最高峰スーパーコピー時計通販専門!7年以上の販売実績を 持つ時計コピー老舗!時計コピーであれば何でも揃えられます コピー時計 時計スーパーコピー通販専門店!時計コピー時計販売通販! コピー時計スーパー コピー等の 最高級のレプリカコピー時計を販売ロレックスコピー,ガガミラノコピー ,IWCコピー ,オメガコピー ,フェラーリコピー ,フランクミュラーコピー ,ベル&ロスコピー ,各種のブランドはコピーを表しますコピーを表して、時計をコピーして、スーパーコピーは代 金引換払いにして、スーパーはブランドをコピーして、スー パーは時計をコピーして代金引換払いにして、スーパーは時 計をコピーして、スーパーは腕時計をコピーして、ブランド はスーパーマーケットを表してコピーして、ブランドのスー パーマーケットはコピーして、ブランドはコピーを表して、 腕時計はコピーします http://www.okakaku.com/brand-5-copy-0.html

  7. dong liu on October 20, 2013 at 8:10 pm said:

    For those looking for pagination and other features like customized sorting and filtering, take a look at this http://datatables.net/ . It is also jQuery-based

  8. How to disable the arrows in the header where the column sorting is disabled?

  9. This table sorter is fast, what about table sorting table with pagination included?

  10. Unfortunately out-of-the-box, TableSorter (like many jQuery plugins) does not create an accessible experience. Specifically what’s missing from TableSorter is any indication to the user as to the fact that the columns are sortable, which column(s) are currently sorted, and in what direction. This can all be indicated to the user of assistive technologies through the use of WAI-ARIA. WAI-ARIA allows you to provide additional semantic information to interface elements that indicates name, state, role, and value to controls. You can see a more accessible version of a sortable table at http://karlgroves-sandbox.com/table-sort/accessible.html This implementation still isn’t perfect but the JS source is well-commented to show some of the techniques used to make it better.

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop