Monthly Archives: May 2010

Recreating your jQuery Sortable() sort order


A reader pinged me with an interesting question.  He was using jQuery the jQuery sortable behavior to allow users to order widgets on a page and then save their layout.  The issue he was having was figuring out how to recreate the layout when the user reloaded the page.

As always there is more than one way to skin a cat, but I came up with a quick demo to illustrate one way to do this.  If we have the user defined sort order it should be easy enough to recreate the view.  I can think of several other ways to accomplish this, but this was the most straight forward way of handling the problem.

For my example I created a div representing my sortable container.  Within the container I created four divs repesenting my sortable children named “div1” through “div4” (I am very creative first thing in the morning).  I then hard-coded a “user defined” sort order that sorts them from “div4” down to “div1”.  Since I know the sort order it is just a matter of looping through my child elements and putting them in their proper place.  This is done by looking at the sort order array and inserting the selected element after the previous element in the sort order.  We skip the first element in the sort order since it obviously will not have a previous element.  The end result being all the divs nicely ordered, just as the user saved them.