Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improving the demo.html #6

Open
ianchanning opened this issue May 3, 2011 · 0 comments
Open

Improving the demo.html #6

ianchanning opened this issue May 3, 2011 · 0 comments

Comments

@ianchanning
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant