blarg
blarg

Reputation: 3893

How to sort <div>s (ascending and descending) and recognise their state?

I'm using Javascript to sort a table that is split into <div>s by their child elements. The code is sucessfully sorting one way, but I need to add the functionality to sort ascending and descending.

I've tried adding a caller to the sorting attributes that signifies which table header is being clicked. I have global variables set up that are set as default to 1 and then they flip between 1 and 2 using an if statement to signify ascending or descending.

The table will only sort ascending and descending once and seems reliant on moving other table headers before the next one can be moved.

JSFiddle of the problem here

 var OrderAuthor = 1;

function sortUsingNestedText(parent, childSelector, keySelector, caller)
{
        var items = parent.children(childSelector).sort(function(a, b)
        {
                var vA = $(keySelector, a).text();
                var vB = $(keySelector, b).text();
                if (caller.data('order_by') == 'author')
                {
                        if (OrderAuthor == 1)
                        {
                                OrderAuthor = 2;
                                OrderSubject = 1;
                                OrderDate = 1;
                                return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
                        }
                        else
                        {
                                OrderAuthor = 1;
                                return (vA > vB) ? -1 : (vA < vB) ? 1 : 0;
                        }
                }
        });
        parent.append(items);
}

Upvotes: 3

Views: 1089

Answers (1)

TheBrain
TheBrain

Reputation: 5608

I would do it like this http://jsfiddle.net/zdCT6/5/

var sortBy = ""
var asc = true

function sortUsingNestedText(parent, childSelector, keySelector) {
     if (sortBy == keySelector) { asc = !asc } else { asc = true }
     sortBy = keySelector
     var items = parent.children(childSelector).sort(function(a, b) {
        var vA = $.trim($(keySelector, a).text());
        var vB = $.trim($(keySelector, b).text());        
        return ((vA < vB) ? -1 : (vA > vB) ? 1 : 0) * (asc ? 1 : -1);           
    });

    parent.append(items);
 }

Way simpler and you don't need to reset those flags there every time plus there is considerable less if branching

Also notice the trim() call. Your text() was returning items with leading space chr that would automatically move that item first/

Upvotes: 3

Related Questions