If you have a need to sort an unordered list alphabetically, it can be done with some JavaScript code. We are mixing some jQuery in this code as well.

$('#sortAlpha').click(function(){
    var sortList = $('#verbList ul');
    var sortItems = sortList.children("li").get();
    sortItems.sort(function(a,b) {
        var compA = $(a).text().toUpperCase();
        var compB = $(b).text().toUpperCase();
        return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    }); // END sort()
$.each(sortItems, function(idx, itm) { sortList.append(itm); });
});

Below is the result. We also employed the use of the jQuery plugin of .shuffle() to randomly mix up the list.

 

Let's review the JavaScript code that was used to sort this list alphabetically.

$('#sortAlpha').click(function(){

This kicks in the function on a click event.

var sortList = $('#verbList ul');

This creates a variable to hold the data from the unordered list

var sortItems = sortList.children("li").get();

This step sets up a variable that retrieves all of the <li> tags in the list. With .get() it retrieves the element and removes it from the parent element at the same time.

sortItems.sort(function(a,b) {

This uses the JavaScript function of .sort() which sorts items in an array

var compA = $(a).text().toUpperCase(); and var compB = $(b).text().toUpperCase();

These two lines take the text and make it all upper case for comparison

return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;

This moves the itmes in the list, comparing each as it iterates through the list. The question mark ? is the Ternary Operator in JavaScript. It replaces an if statement. It takes the condition and two expresions that will evaluate to true or false. What this says is that if the variable compA is less that compB (lower in the alphabet), then use -1. If not, use a positive 1.

$.each(sortItems, function(idx, itm) { sortList.append(itm); });

Using the $.each() method, iterates through the list and appends it to the sortList variable, which is the unordered list set up earlier.

});

Closes the click function.

 

Other ways to sort lists using jQuery plugins

Use the TinySort Plugin. Get it here: http://tinysort.sjeiti.com/  Download the .js file and link to it in your <head> section of your HTML document.

<script src="/js/jquery.tinysort.min.js" type="text/javascript" ></script>

This jQuery plugin will sort any nodetype. Here is the very simple code to make this work.

$('#sortAlpha').click(function(){
    $('#verbList ul li').tsort();
});

 The .tsort() function will also accept arguments, such as sorting on a <span> or to order by alpha decending, for example. It also will sort numbers. Refer to their website for all the available parameters.