Home & blog  /  Scripts  /  view post  /

Animated table sort (REGEXP friendly)

Note: this script is currently unsupported. You are free to use it, but, due to its complexity, there are some bugs. Some people report it working fine, others (with large tables, especially), have issues.

Overview

This plugin allows you to animatedly sort a table based on a column's s, or on the content/value of a child/descendant element within those s. The various s fly to their new homes, giving a nice effect. It also supports sorting on REGEXP matches. You can also control whether row relationships are maintained, whether it sorts on ascii or numeric and ascending or descending.

Usage & parameters

Call tableSort(params) on a table returned by a jQuery selector.

$(selector).tableSort(params);

...where params is an object of property/value pairings, including:

onCol (int, required) - the index of the column in your table to sort on (not zero-indexed)

keepRelationships (bool, default: false) - if true, row relationships wil be maintained. That is, the sibling s will move also

regexp (RegExp, default: null) - a string representing a regular expression (/pattern/) to sort on instead of the complete contents of the . Useful with regexpIndex - see below.

regexpIndex (int, default: 0) - if sorting on a regular expression, this is the index of the returned array of matches to use for the sort, should it return more than one match. See below for an example of this, where a regexp sub-pattern is used.

child (string) - sort on the content/value of a child/descendant element within each , rather than on the s themselves. This should be a selector string to match that element. See notes for more info.

sortType (string, default: ascii) - either 'ascii' or, if wanting to sort numerically, 'numeric'

sortDesc (bool, default: false) - if true, the sort will be done in descending order, not ascending

Example 1

Click the column headings to sort the table based on that column

Place County Phone code Approx. population
Nottingham Nottinghamshire 0115 292400
Luton Bedfordshire 01582 203800
Huddersfield Yorkshire 01484 146234
Carlisle Cumbria 01228 103700
Brighton East Sussex 01273 155919
Woking Surrey 01483 62796
Basingstoke Hampshire 01256 82913
Rhyll Clwyd 01745 24889

Here's the code applied to the links in the s:

1//column 1 - by place name

2$('#example1_table').sortTable({

3     onCol: 1,

4     keepRelationships: true

5});

6//column 2 - by county

7$('#example1_table').sortTable({

8     onCol: 2,

9     keepRelationships: true

10});

11//column 3 - by phone code

12$('#example1_table').sortTable({

13     onCol: 3,

14     keepRelationships: true,

15     sortType: 'numeric'

16});

17//column 4 - by approx. population

18$('#example1_table').sortTable({

19     onCol: 4,

20     keepRelationships: true,

21     sortType: 'numeric'

22});

Example 2 - REGEXP

To illustrate better how the regular expression parameters can be useful, consider the following example.

Product category
Playstation 3 games (164)
XBox 360 games (94)
Nintendo Wii games (142)
Nintendo DS games (89)
PC games (221)
Apple Mac games (18)

This simple table shows a number of product categories and, for each, the number of products in each one.

Here, we want to sort on the number of products, not on the whole contents of each . Stipulating this in a suitable regular expression string passed in the regexp parameter allows this.

Click the link in the to see the demo.

Here's the code behind this example:

1$('#example1_table').sortTable({

2     onCol: 1,

3     sortType: 'numeric',

4     sortDesc: true,

5     regexp: /\((\d+)\)/, //match just the number of products

6     regexpIndex: 1, //sort on just the number, not brackets too

7     keepRelationships: true

8});

Note we specify regexpIndex as 1 because we our regexp pattern returns an array of matches containing two elements, and we want to sort on the number in isolation, i.e. the sub-pattern, not on the surrounding brackets as well.

If this is Greek to you, click here for more information on Javascript regular expressions.

Notes

DOM

Since s are very fixed elements and aren't animatable, the animation is done by some DOM-scripted

s, which animate to their new homes then repopulate their new homes.

These complimentary elements are removed once the animation is complete, leaving you with a legitimate table, each of the s of which genuinely contain the content they appear to. This means you can perform further traversal or manipulation on the table without issue.

UPDATE - 17/07/2010: sort on child element

Following a request, you can now sort on the content/value of a child/descendant element within each by passing a selector string to match that element in a new parameter, child.

So for example, if the s in column one each contained a text field, and you wanted to sort the table on the current values in those fields, you could run the following:

1$('#example1_table').sortTable({

2     onCol: 1,

3     keepRelationships: true,

4     child: 'input'

5});

Important: ensure child matches only one element in each , or the sort will fail. So in the above example, if each contained more than one , the script would be break. To avoid this, be more specific, e.g.

1child: 'input:first-child'

2//or

3child: '#myField'

4//etc

post new comment

Comments (89)

Alex, at 17/09/'10 23:13, said:
Hi, nice thing, ive modified it a little bit to make it look more friendly:
http://dl.dropbox.com/u/2595104/JS/tableSort.rar
Frank, at 20/09/'10 11:38, said:
Great!
It would be nice to have something like "sortOrder: toggle". Means after each click on the same column the order changes.
Mitya, at 20/09/'10 12:30, said:
Good idea - might be something I implement in the near future.
Frank, at 22/09/'10 12:12, said:
Hi Mitya,
I would recreate the previous sorting (column and order) when the user returns to the table from surfing somewhere.
The question is: Is there a callback or anything to get the information of current sorting?
Thanks, Frank
Mitya, at 22/09/'10 15:09, said:
This can be achieved by appending the following line to the 'PREP' section in the code:

$(this).get(0).tableSortParams = params;

You can then interrogate any of the currently effective parameters (see above on this page) for the given table with something like:

alert
Frank, at 24/09/'10 06:48, said:
It would be nice to display a little arrow icon at the header cell indicating current sort direction, like windows explorer.
Maybe it is possible to link own icons?
Mitya, at 24/09/'10 09:55, said:
True. This could be easily coded in - if your JS level is intermediate-advanced this shouldn't be difficult. Else I'll add it when I have time.
Frank, at 24/09/'10 11:46, said:
Almost high intermediate!
;-)
Nick, at 29/09/'10 10:58, said:
Great! But doesn't work in Opera 10.61!
Mitya, at 29/09/'10 11:05, said:
Hi Nick. I currently work and build in Opera 10.61 and it works OK for me. Do you get a specific error?
Divyesh , at 29/09/'10 20:14, said:
it is really good. I will use near future..

Thanks
Agence Index Web Marketing - Montreal, at 2/10/'10 07:42, said:
This is exactly what I was looking for.

I'll try to combine this with a non-profit organization I am volunteering for.

Thanks for your outstanding contribution!
Jonathan, at 13/10/'10 04:26, said:
Great Work!  I, however, can get it too work in safari and chrome browsers, but when I run it as an adobe AIR application, it does not work.

It might have something to do with my custom AIR setting for links.  But if anyone has insight, and if it is an "adobe AIR incompatibility", please let me know! 

Thanks for any help,

Jonathan
Jonathan, at 13/10/'10 04:26, said:
Great Work!  I, however, can get it too work in safari and chrome browsers, but when I run it as an adobe AIR application, it does not work.

It might have something to do with my custom AIR setting for links.  But if anyone has insight, and if it is an "adobe AIR incompatibility", please let me know! 

Thanks for any help,

Jonathan
Jonathan, at 13/10/'10 06:34, said:
Concerning my above post!  I was able to change the "href=" attribute to the "onclick=" and my problem was solved!
Henrik, at 18/10/'10 08:10, said:
Hi,

This is amazing dude, but I have a question..

Is it possible to do this without any sort?

I'm currently working on a project where I need to move a  to the top of the .. Currently I do this by using "fadeIn()" and "prependTo()" - But if I could make it by sliding it to the top it would be perfect!

Please contact me :)

- Henrik
Mitya, at 18/10/'10 10:18, said:
Hi Henrik

Presently it's not set up to do that, but could be with some tweaking. How's your JS level? You could tweak it to do what you need.

Alternatively you could force it to sort in such a way that only the row you wanted to move actually moved. This would be awkward, admittedly.
mike johnson, at 26/10/'10 00:31, said:
Great piece of code. I've gotten it to work intermittently, but keep getting the following error:
Error: currTD.get(0) is undefined
Source File: 
Line: 151

Thoughts?
Dilip Nikam, at 28/10/'10 05:58, said:
Hi,

Awesome Implementation.  

Is this is possible to sort multiple column ? 
Mitya, at 31/10/'10 15:21, said:
Dilip - sorry for the late reply. No, unfortunately this is not possible presently.
Mike Johnson, at 1/11/'10 13:24, said:
Any thoughts on my previous question? It seems to be happening on the first column with sortable data. (Varies based on query).

Thanks,
Mike
Mitya, at 1/11/'10 13:43, said:
Mike - sorry, I thought I'd replied to that. Obviously not. Yeah the script isn't perfect; I'm pretty sure I didn't get these errors when I first made it, but it seems now I do, so I guess I just never noticed them before. I'll get round to fixing this, but I remember this one being one of the hardest scripts I've ever built so I'm not looking forward to that! Stayed posted.
Frank, at 9/11/'10 09:31, said:
Hi,

after the user sorts a column it would be nice to sort in opposite direction on the next click on the same column header.
How can I achieve this?

Thanks,
Frank
Frank, at 17/11/'10 07:19, said:
Hi,

Regarding my previous posting:
After the user sorts a column it would be nice to sort in opposite direction on the next click on the same column header.

Do I have to make changes in your code or is it possible to achive this without changing your code?
Could you give me a short hint?

Thank you,
Frank
Saul, at 17/11/'10 16:37, said:
 -

This is how I did it. Replace the 'Sort Values Array' portion of the code with the following :


if (params.sortType == 'numeric') {
       valuesToSort.sort( function(a, b) {
              a.replace(/[^\d\.]/g, '');
              b.replace(/[^\d\.]/g, '');
              return a - b;
              });
       } else { valuesToSort.sort(); }

if (params.sortDesc) { valuesToSort.reverse(); } 

       var thisTD = $(this).find('th a:eq(' + (params.onCol - 1) + ')');
       if ( thisTD.hasClass('tableSort_toggled')) {
              valuesToSort.reverse();
              }
       thisTD.toggleClass('tableSort_toggled'); 


Cleans it up a little and gets the job done. Thanks, Mitya!
Frank, at 18/11/'10 07:10, said:
Saul,

thank you very much! Your solution works like a charm.

Frank
Mitya, at 18/11/'10 22:25, said:
Saul - thanks for sharing this. I'll be featuring it in a blog tomorrow or Saturday.
Merdan, at 23/11/'10 12:26, said:
it fails on Linux systems. for example on my:

Ubuntu 10.04
with Opera 10.60
Mitya, at 23/11/'10 13:26, said:
As I keep saying, it's not perfect, and it's a very tough script to get right. Hopefully eventually I'll patch it up.
dr john, at 30/11/'10 10:22, said:
Is it possible to offer ascending and descending sorts - say one click ascending, double click descending, or first click on a header sorts ascending, second click goes descending? (My js skills have faded away from lack of use, so it's currently beyond me)
Mitya, at 30/11/'10 10:29, said:
Hi Dr John - see here: https://mitya.co.uk/blog/2010/Nov/Table-sorter-toggling-sort-direction-143
anna, at 1/12/'10 12:21, said:
Hi,
This is fantastic. Guys I have come across scenario like this.
When it's like this, it's not working. Any solutions for this?
mitya, at 1/12/'10 12:30, said:
Anna - as I've said above, this script is not perfect and it needs further bug testing. Unfortunately this is a very complex script that is proving hard to pin down and get right.
FRED, at 5/12/'10 03:35, said:
good job
ej, at 6/12/'10 01:50, said:
I hope this can support 
  • sarathkrishna, at 6/12/'10 18:57, said:
    wow........!!
    Abram, at 21/12/'10 22:53, said:
    Awesome post! Thanks
    battery, at 22/12/'10 05:40, said:
    Thank you for sharing program 
    John_www, at 4/01/'11 18:48, said:
    What is the maximim number of rows that it can deal with? I am having problems when it goes over one hundred rows, and need to show that many (and more), no pagination.
    Thanks.
    Rob, at 5/01/'11 11:39, said:
    Any update on the first column bug?
    Daniel Hölbling, at 10/01/'11 11:42, said:
    Hi,
    cool script. Works fine for me right now for most cases.
    But I am seeing a little bug where sometimes the script adds sorts table headers too so they disappear from my list in Google Chrome.
    
    I'll try to pinpoint the bug and contribute the fix.
    
    Thanks for the script.
    
    greetings Daniel
    digital camera battery, at 24/01/'11 08:03, said:
    Thank you for sharing program I just found it ! 
    Raghib Suleman, at 10/03/'11 05:02, said:
    its wonderful table sorter... good work
    
    Freddy, at 11/03/'11 10:28, said:
    Super....Awesome work..
    RAT, at 2/05/'11 04:07, said:
    Hi 
    I Love your site. but only one this I don't like is people writing Link on your comment.  Remove HTML Link before display comments.
    
    Love to see more nice staff in future.  
    Peter, at 14/05/'11 18:18, said:
    Awesome, I love your script. The thing is, I'm used to TableKit, but that one is Prototype based. So I wanted a way to create the sort links in the table headers automatically, like TableKit works by adding the "sortable" class to the table.
    
    So here's a small piece of jQuery that adds an ID to all tables that have a "sortable" class, and automatically adds the links to the table headers for sorting.
    
    Enjoy!
    
    $(window).ready(function() {
           $(".sortable").each(function(tableIndex,table) {
                  $(table).attr("id","sortable_table_"+tableIndex);
                  $(table).find("th").each(function(thIndex,th) {
                         $(th).html(""+$(this).html()+"");
                  });
           });
    });
    Peter, at 14/05/'11 18:31, said:
    Also, in addition to Saul (17/11/'10 16:37), to display images which indicate the direction of the sorting, use this piece of code for the "Sort values array" part;
    
    if (params.sortType == 'numeric') {
           valuesToSort.sort( function(a, b) {
                  a.replace(/[^\d\.]/g, '');
                  b.replace(/[^\d\.]/g, '');
                  return a - b;
                  });
           } else { valuesToSort.sort(); }
    
             if (params.sortDesc) { valuesToSort.reverse(); } 
    
           var thisTD = $(this).find('th a:eq(' + (params.onCol - 1) + ')');
           if ( thisTD.hasClass('tableSort_toggled')) {
                    valuesToSort.reverse();
                    thisTD.addClass('desc');
                    thisTD.removeClass('asc');
             } else {
                  thisTD.addClass('asc');
                  thisTD.removeClass('desc');
             }
          thisTD.toggleClass('tableSort_toggled');
    
    This adds a desc or asc class to the th. You can define your own pictures, or add jQuery UI (it has built in images & css for tables, including these arrows).
    
    Cheers!
    abdeljalil, at 23/05/'11 23:17, said:
    hi i will sort my table by date !! it's possible ??
    air max 90, at 10/07/'11 16:08, said:
    Nice blog and the article are simply superb. The article posted was very informative and useful. You people are doing a great job. Keep going.
    
    Lawyer Townsville, at 12/07/'11 13:53, said:
    I have no any doubt after read this nice article.It would be nice to display a little arrow icon at the header cell indicating current sort direction, like windows explorer.
    Debbie Austin, at 12/07/'11 14:02, said:
    Thanks for updating to let us sort on child value. With that update, this little plugin has just what I need.
    Sam Summer, at 13/07/'11 02:19, said:
    The script seems to simple. It's like it was right in front of my face. The header cell was the key.
    Jon Long, at 15/07/'11 00:54, said:
    I needed to execute a piece of code right after the sorting had finished, so I modified this plugin to include a callback that lets you know when it's done.
    
    Just remove the "jQuery.fn.tableSort_cleanUp" function, and replace this line:
    
    if (done == valuesToSort.length-1) thiss.tableSort_cleanUp();
    
    with this:
    
    if (done == valuesToSort.length-1){
           thiss.find('td').each(function() {
                  if($(this).get(0).toTD) $($(this).get(0).toTD).get(0).newHTML = $(this).children('div').html();
           });
           thiss.find('td').each(function() { $(this).html($(this).get(0).newHTML); });
           $('td.tableSort_TDRepopulated').removeClass('tableSort_TDRepopulated');
           thiss.find('.sortOnThisCol').removeClass('sortOnThisCol');
           thiss.find('td[newHTML]').attr('newHTML', '');
           thiss.find('td[toTD]').attr('toTD', '');
           if (typeof callback == 'function') { // make sure the callback is a function
             callback.call(this); // brings the scope to the callback
           }                                   
    }
    
    
    Let me know if you ever put it up on GitHub and I'll gladly contribute :)
    
    Thanks again for this awesome plugin!
    
    Mitya, at 15/07/'11 10:45, said:
    Nice one, Jon Long - thanks.
    nike dunks, at 16/07/'11 02:54, said:
    Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it.
    cute handbags, at 17/07/'11 05:06, said:
    The guide and tips are very useful for my website building
    Roy, at 17/07/'11 05:09, said:
    I love the animation scrips you made here
    
    Thanks:
    cartilage" target="_blank">http://cartilagepiercing.us/">cartilage piercing
    pennsylvania, at 17/07/'11 17:09, said:
    I use a lot of tables on my sites. It is the easiest way of creating the effect I want. I need to take my time and have a look at this great piece, thanks.
    abi, at 26/07/'11 11:54, said:
    Hey, first of all I would like to say that your script is awesome and has helped me a lot.
    
    I use the script to sort a table with text inputs in it.
    Now, if I fill the input with some text and then press the sort button the table is sorted but the text in the text inputs is gone and I need to still be there after i sort.
    
    does anyone know a solution?
    
    thanks in advance.
    Dhiraj, at 26/07/'11 14:58, said:
    Hi, I am having problem while sorting the table if one of my columns contain some NULL values and 0's in between a column of sortType: 'numeric'.
    
    Is there a workaround that I can add to the code to make it work? I am not very good with java scripting. Kindly reply.
    
    Thanks,
    Dhiraj Chawla, at 26/07/'11 14:59, said:
    Say I have table as follows:
    
    Item   Price
    abc     10
    def      8
    ghi      0
    jkl       
    mno    0
    
    Now if I sort, I get,
    Item Price
    ghi    0
    mno  0
    jkl     
    def    8
    abc    10
    
    instead of ,
    Item Price
    jkl    
    ghi    0
    mno  0
    def   8
    abc   10
    Fake Oakley Sunglasses, at 29/07/'11 15:12, said:
    The guide and tips are very useful for my website building
    dsf
    Fake Oakley Sunglasses, at 29/07/'11 15:14, said:
    its wonderful table sorter... good work
    
    JP, at 3/08/'11 00:13, said:
    As of 2/8/'11, the function name is inconsistent in the documentation -- sometimes tableSort and sometimes sortTable. I understand the real function to call is sortTable.
    JP, at 5/08/'11 20:37, said:
    The noAnim parameter is undocumented -- not sure if that's intentional.
    uwedding, at 10/08/'11 04:06, said:
    Thank you for this post. It has definitely helped in my knowledge. I’m fairly certain I’ll arrive back to this blog site. Many thanks once again
    
    software qa, at 10/08/'11 11:15, said:
    Useful script examples. Now trying to use them on my projects. 
    Best Regatds, Omen
    Kenny, at 11/08/'11 23:55, said:
    Really useful script.. Did you ever find the cure to the the currTD.get(0) is undefined error.
    I have tried your script on a little table i am playing with and it will sort column 2 up and down(thanks to sauls added part) but column 3 and 4 produce the error. Column 1 does not need to be sorted although i have tried that and get an error.
    raybansunglasses, at 18/08/'11 02:46, said:
    Your do have some unique ideas here and I expect more articles from you.
    cartier love outlet, at 9/09/'11 07:45, said:
    great posts and thanks a lot for sharing
    wanghui, at 20/09/'11 09:41, said:
    nice thing,ive downloaded it,i am an new learner.thank you...
    3Nex, at 19/10/'11 20:40, said:
    Seems the "currTd.get(0) is undefined" occurs when you have stuff other than text in your table (personally i need images in one column). Too bad it doesn't work with those, otherwise an awesome script!
    Mitya, at 20/10/'11 09:58, said:
     - this script is currently unsupported as there are known issues. You are welcome to use it "as is", i.e. if you can get it to work for you.
    New Era hats, at 1/11/'11 16:03, said:
    very good post,thank you very much
    Ban Terbaik GT Radial, at 3/11/'11 03:34, said:
    Thanks for sharing your article. I really enjoyed it. I put a link to my site to here so other people can read it.
    wholesale new era hats, at 8/11/'11 03:52, said:
    I was looking for this specific the other day. i won’t commonly post throughout forums but i want to to say thank you!
    Goyal, at 20/12/'11 09:07, said:
    If table column data is a link then sorting logic does not work. Even if i just say "test_cell_data" and have multiple such table column data with different values in  and , sorting the column does not work. Is there any way to get rid of this issues..??
    Goyal, at 20/12/'11 19:03, said:
     - though I confess I don't know fully what you mean, this script does have known issues, so I'm afraid I don't support it. It works for some people, not others. I will be re-writing this script in early 2012, though I recall it fried my brain the first time around, so I'll, er, look forward to that.
    Ashik, at 16/01/'12 14:46, said:
    i have a table to sort, 
    eg: 
    
    York
    10
    5
    10
    6
    Here i need to do the multiple div values sorting, ie here second row must moved to first position , how can i solve this with jquery animated script. Thanks for your support ---------Not Working below script---- $('#table').sortTable({onCol: 1, keepRelationships: true, sortType: 'numeric',sortDesc: true,child: '.c1 .c2'});       
    Warren, at 14/02/'12 17:11, said:
    Do larger tables have issues with this, mine is 50+ rows with 2 columns and the animation does not work. I have your demo right above it and that works fine. 
    Warren, at 14/02/'12 18:29, said:
    Is there a way to control the time the animation occurs, as I am not sure why, but larger tables do not animate, they sort, but seems to hang for a second and then just apear.  Can I add a time factor to help it slowly do it?
    Mitya, at 14/02/'12 18:43, said:
     - sorry but this script is unsupported. See previous comments from me. I have now added a header at the top of this page to make this clear. You are free to use it; some people get it working fine, others have issues with it. It needs re-writing.
    Snapback Hats, at 10/04/'12 02:45, said:
    You can also control whether row relationships are maintained,
    alifellod, at 24/05/'12 04:32, said:
    Great!
    Fabien Rigaux, at 11/06/'12 14:46, said:
    The same script with two more optional parameters :
    - animationDuration : TD animate duration in milliseconds
    - callback : function to call after sortTable has been done
    
    Example :
    --------------
    
    
    "Plugin modifications" :
    ---------------------------
    jQuery.fn.sortTable = function(params) {
                  ...
                  animateOn.children('div').animate({top: moveBy_top}, !params.noAnim ? params.animationDuration : 0, null, function() {
                         if ($(this).parent().is('.sortOnThisCol') || !params.keepRelationships) {
                                done++;
                                if (done == valuesToSort.length-1) thiss.tableSort_cleanUp(params.callback);
                         }
                  });
           }
    };
    
    
    jQuery.fn.tableSort_cleanUp = function(callback) {
           ...
           if (typeof(callback) != 'undefined') {
                  callback();
           }
           
    };
    james, at 13/06/'12 11:12, said:
    wonderful feature.. really insuperable  things thanks for sharing
    anne, at 13/06/'12 11:15, said:
    superb, great work
    TISA Snapbacks, at 9/07/'12 12:22, said:
    whether it sorts on ascii or numeric and ascending or descending. 
    Objet publicitaire, at 25/10/'12 04:21, said:
    Thank you for this article.
    post new comment