Toggling ASC/DESC sorting using Animated table sort plugin for jQuery



Just few mins ago, from a tweet of Tareq Hasan, I came to learn about Animated Table Sort plugin for jQuery. Seeing the demo I was stunned and decided to implement on a project I was working right then!

After implementing, I see it can sort in one way. Either ascending or descending. If we set the parameter to

sortDesc: true

it sorts the table in descending order, otherwise ascending order. But, I wanted in both way. I mean, after clicking on the header, it should toggle between order. Suppose, on first click, it sorted ascending order. However, the second click should sort in descending order.

I did not see anything for this in its documents. But it is fairly easy to do with jQuery’s toggle event. I have also used dynamic selectors. Here is the javascript code that I have used


$('#tbl_proof > thead > th').toggle(function (){
ind = eval($(this).index())+1;
$('#tbl_proof').sortTable({
onCol: ind,
sortDesc: false,
keepRelationships: true
});
}, function () {
ind = eval($(this).index())+1;
$('#tbl_proof').sortTable({
onCol: ind,
sortDesc: true,
keepRelationships: true
});
});

This plugin counts the indexes from 1 but jQuery returns from 0. That’s why I have added 1 with the returned index. The above example shows, during first click, it will sort on ascending. the next click will sort descending order. See the following video for an illustration :).

  • http://www.30.com.au steve

    I have just chatted to Andy from Mitya.co.uk regarding the asc/desc switch using jquery.

    I like your demo, but can you explain how and where you amended the code you show above.

  • The HungryCoder

    hi steve,
    Do you already use this plugin? in that case, your need to amend the code where you have triggered this plugin! If not, then copy the above code in your page’s just before section. However, you may need to structure your table as I have done or you have to update the selectors in the code.

    in the code I have used tbl_proof as table id, table structure was like:

    HEAD 1
    Value 1

    thanks

  • http://www.beststagweekend.com/ Tom

    Nice dome. It’s been I’ve been programming last time…

  • http://www.30.com.au steve

    still havent got this to work, could you post some code.