REQUEST A DEMO

Using jQuery to Sort a List

I needed to add a new feature today, and wanted an easy client-side solution. Since I use jQuery in the project already, I searched and found a good starting point in a blog post by Bill Richards.

 

The code I found adds a function and a sort handler that can be applied to a list.

 

jQuery.fn.sort = function() {

    return this.pushStack( [].sort.apply( this, arguments ), []);

};

function sortAlpha(a,b){

    return a.innerHTML > b.innerHTML ? 1 : -1;

};

 

 

Here is a simple example of the HTML I am working with:

 

<ul id=”caseListing”>
<li>
<div id=”1″>
<a href=”/Cases/Show/1″>Case 1</a>: need help with VPN connection
</div>
</li>
<li>
<div id=”3″>
<a href=”/Cases/Show/3″>Case 3</a>: blue screen of death upon login
</div>
</li>
<li>
<div id=”6″>
<a href=”/Cases/Show/6″>Case 6</a>: Computer has no power
</div>
</li>
</ul>

 

 

When the page loads, all of the list items are sorted by the id number of the case. Since I need to be able to inverse the order of a list of items after it is displayed, I added this anchor element to change the sort order:

 

<a id=”sortOrder” href=””>Sort Desc</a>

 

 

For the javascript required, I added another sort handler for reversing the order, and added code for the hyperlink to initiate the sort function. The jQuery code I end up with looks like this:

 

<script type=”text/javascript”>

jQuery.fn.sort = function() {
return this.pushStack([].sort.apply(this, arguments), []);
};

function sortAscending(a, b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
};

function sortDescending(a, b) {
return a.innerHTML < b.innerHTML ? 1 : -1;
};

$(document).ready(function() {
    $(“#sortOrder”).toggle(
function() {
$(‘#caseListing li’).sort(sortDescending).appendTo(‘#caseListing’);
$(this).text(“Sort Asc”);
},
function() {
$(‘#caseListing li’).sort(sortAscending).appendTo(‘#caseListing’);
$(this).text(“Sort Desc”);
});
});

</script>

 

 

Each time the anchor tag is clicked, the order of the list elements is reversed. The toggle event handler for the anchor element does most of the work. It calls the correct sort handler, and updates the text of the anchor tag to keep it clear for the user.

 

This ends up being a very light-weight, fast client side sorting solution for small sets of list items.

 

 

 

Technorati Tags: ,