Sorting buttons within a group
We can use the sortable()
interaction widget to provide the user which some flexibility. Why not let the user move buttons around? Especially given the small amount of code it takes.
Getting ready
We'll use a list to organize our buttons, as follows:
<ul> <li><a href="#">Button 1</a></li> <li><a href="#">Button 2</a></li> <li><a href="#">Button 3</a></li> </ul>
We'll use the following CSS to fix the list layout to better display button widgets.
ul { list-style-type: none; padding: 0; } li { margin: 4px; }
How to do it...
The JavaScript code to make this happen is actually quite miniscule—we create the buttons, then we apply the sortable interaction widget.
$(function() { $( "a" ).button(); $( "ul" ).sortable({ opacity: 0.6 }); });
At this point, we're able to drag-and-drop buttons—but only within the designated container element, in this case, ul
.
How it works...
The first thing we're doing in this example, once the document is ready, is creating the button widgets. We're using anchors as the underlying element, which works just as well as button
elements. You'll notice too, that we've structured the button widgets on the page inside of an unordered list. The styles added to the page just remove the list indentation and the bullets. But the ul
element is what we're targeting for the sortable interaction. By default, the sortable widget looks for all child elements and makes them the sortable items, in our case, these are li
elements. The opacity
option specified in the example tells sortable
to change the visual opacity of the element being dragged.