Sortable Lists

Novice to Ninja Chapter 8 Example 2 (page 298)

by beej

HTML

<ul class="sortable">
    <li><a href="#">Beau Dandy</a></li>
    <li><a href="#">Glendatronix</a></li>
    <li><a href="#">BMX Spandex Corp</a></li>
    <li><a href="#">Maxwell Zilog</a></li>
    <li><a href="#">Computadors</a></li>
</ul>
<form>
    <input type="button" id="ascending" value="Asc" />
    <input type="button" id="descending" value="Desc" />
</form>

JavaScript

var SORTER = {};
SORTER.sort = function(which, dir) {
    SORTER.dir = (dir == 'desc') ? -1 : 1;
    $(which).each(function() {
        var sorted = $(this).find("> li").sort(function(a, b) {
            return $(a).text().toLowerCase() > $(b).text().toLowerCase() ? SORTER.dir : -SORTER.dir;
        });
        $(this).append(sorted);
    });
};
$("#ascending").click(function() {
    SORTER.sort('.sortable');
});
$("#descending").click(function() {
    SORTER.sort('.sortable', 'desc');
});