How to Create a Sortable Interface in CSS3 - dummies

How to Create a Sortable Interface in CSS3

By John Paul Mueller

Certain kinds of sorting are easy for computers to do, and you want your CSS3 coding to create that situation. For example, a computer can put items in alphabetical order much faster than a human can, especially when the list is long.

However, sorts aren’t always logical. You may want the user to sort a list of items by personal preference or other criteria that the computer can’t even understand. In these cases, you need a means of allowing manual sorts — and this example gives you just what you need.

The following example lets a user sort items by unspecified criteria. (You can find complete code for this example in the Chapter 06Interactions folder of the downloadable code as SortContent.HTML.)

function ShowResults()
 // Create the ouput string.
 var Output = "The sort order is:n ";
 // Locate each of the required items and
 // add them to the string.
 $("#SortMe p").each(
 function(index, element)
  Output += element.innerHTML.substr(74);
 // Display the result.

The sortable() call is all that you need to do to make the list visibly sortable. The user can place the elements, whatever those elements might be, in any order desired. To make this call work, however, you do need to create a container — a <div> in this case — and a list of items, specifically <p> tags. The SortMe id goes with the <div>.

Accessing the items in order is also a requirement. Otherwise there’s no point in letting the user sort the items. In this case, it’s actually easier to use other jQuery functionality to obtain the list of elements in the order in which they appear and process them that way.

ShowResults() demonstrates one technique for performing this task. You begin by creating the appropriate selector, which begins with the <div>, SortMe, and ends with each <p> tag it contains. The anonymous function receives both an index and an element argument. By checking the innerHTML property of the element, you can obtain the moniker for that <p> tag. The result is displayed in a dialog box.

This example also makes use of a special jQuery UI CSS style. This style creates a double-ended arrow that helps the user understand that each item can move up or down in the list. You create it using a <span> like this:

<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>

You can find a list of these icons at jQuery UI CSS Framework. It’s important to create icons that match the way your list appears onscreen.