padolsey-archive / jquery.fn

A collection of jQuery plugins
http://james.padolsey.com
The Unlicense
1.1k stars 723 forks source link

Improving the demo.html #6

Open ianchanning opened 13 years ago

ianchanning commented 13 years ago

The demo html sorting doesn't work properly when switching between columns. It will sort one ascending and the next descending. It should always sort the column asc first. I've put the jquery below to do this, with the following fixes.

  1. I've added a $(function () {}); around the jquery - it fails when moving it to a separate script otherwise
  2. I've added the use of classes to store the sort order (requires adding the sort class to the html)
  3. I've added the ability to sort on img elements (you might want to ignore this)

    $(function () {
    var th = jQuery('th.sort'); // don't assume all th are sortable
    
    th.click(function(){
       var header = $(this),
           index = header.index(),
           inverse = header.hasClass('asc');
    
       header
           .closest('table')
           .find('td')
           .filter(function(){
               return $(this).index() === index;
           })
           .sortElements(function(a, b){
    
               // allow img sorting on alt text
               var aImg = $(a).find('img');
               var bImg = $(b).find('img');
    
               if (aImg.size() > 0) {
                   a = aImg.first().attr('alt');
               } else {
                   a = $(a).text();
               }
    
               if (bImg.size() > 0) {
                   b = bImg.first().attr('alt');               
               } else {
                   b = $(b).text();
               }
    
               return (
                   isNaN(a) || isNaN(b) ?
                       a > b : +a > +b
                   ) ?
                       inverse ? -1 : 1 :
                       inverse ? 1 : -1;
    
           }, function(){
               return this.parentNode;
           });
    
       if (!header.hasClass('asc') && !header.hasClass('desc')) {
           // remove any other sorting
           $('th.asc').removeClass('asc');
           $('th.desc').removeClass('desc');
           // set asc
           header.addClass('asc');
       } else {
           // swap asc|desc
           header.toggleClass('asc').toggleClass('desc');
       }
    });
    });

Thanks,

Ian