An Architect's View

CFML, Clojure, Software Design, Frameworks and more...

An Architect's View

A quick jQuery sortable tip

March 11, 2009 ·

[Originally published in a slightly different format on the Broadchoice ArgumentCollection blog]
The Broadchoice Community Platform has a number of "modules" (applications) that you can add to a page and one of those is a list of documents for download (or external links). You add the module to the page and then select documents (from your document library) to add to that module. In previous releases, authors had to add documents in the order that they wanted them to appear on the (generated) web page. We looked at a number of UI options for allowing authors to "rank" the documents within the module but felt most of them were fairly clunky, involving entering ranking numbers to reorder things or up/down arrows requiring authors to move documents one position at a time. Ugh! Ray pointed me at one of the cool jQuery UI interactions: sortable. It allows you to mark a "container" tag (e.g., a div) as sortable and then users can drag'n'drop the "child" elements into the order they want. You can attach event handlers that fire at various points in the drag'n'drop operation. Here's how we do it:
<div id="sortable">
<cfloop query="documents">
<div id="doctag_#documents.id#" onMouseOver="setCursor(this,'move')" onMouseOut="setCursor(this,'auto')">
#documents.name# ... etc ...
</div>
</cfloop>
</div>
That's all you need in the HTML. Then you add the following JavaScript:
$('#sortable').sortable({
update: function(event,ui) {
jQuery.get('/updateRank.cfm?' + $('#sortable').sortable('serialize'));
}
This causes two things to happen:
  1. jQuery marks the sortable div contents as being, well, sortable!
  2. jQuery adds an event handler for update - when the drag'n'drop operation completes - that invokes a URL on the server, passing in the serialized data from the children of the sortable div, i.e., the id values as a list in the new order: doctag[]=1,3,4,2. It assumes an underscore as a separator.
The server side code simply updates the module data to put the documents in the specified order.

Tags: coldfusion · jquery

0 responses