Friday, October 25, 2013

jQuery UI: Sortable Accordion Sections

Using a fixed ordering for your accordion sections is all well and good, but why not let the user sort the sections themselves? Seems like a good idea to me — especially with the help of sortable, it should be a straightforward customization of the accordion widget to enable this behavior. There is, however, one gotcha that makes this customization nontrivial. The DOM structure of the accordion section has a header, followed by the content div. How should we make sortable deal with that?

The answer, is to wrap, and unwrap the accordion header in content sections in a div element. This makes the sortable interaction attainable. Otherwise, we would have to implement some tricky movements after the header gets sorted — you don't want any part of that nonsense. The example code simply adds a new sortable option to the accordion widget. When sorting is enabled, we wrap each header and content element in a div. Then we make the accordion sortable along the y axis.

In the accordion _destroy() method, we destroy the sortable, unwrap the accordion sections, then call the base method which takes care of destroying the widget. What's interesting about this customization is that, after a sortable interaction takes place, we don't need to call the refresh() method. That's because the header expects it's content to be the next sibling node. We don't change that structure, we keep it intact and relocate it in response to user actions.

No comments :

Post a Comment