Variable Visions

Published Thu. Jan. 01, 1970

jQuery UI Sortable List with Cookie memory

Use .sortable, .cookie, .split(','), .appendTo, and .length

In a previous tutorial I showed you how to set up a "garage doors" technique in jQuery using the toggleClass method with two CSS rules with different heights. You can use either jQuery Easing or CSS transitions to smooth the door opening and closing. This also relates to the basic lesson Relative and Absolute Positioning in CSS.


This time, I take it one step further.

I client liked the opening and closing doors to reveal more text, but they wanted something different...for the end user to be able to reorder the grid tiles (or standard list if you didnt float the li's to make a grid).

For this, I looked to jQuery UI and the .sortable method.

.sortable was fairly easy to get working, once linked to jQuery Core AND jQuery UI files. But every time I refreshed the page, my manipulated new order was forgotten. That was no good.

So I then looked to jQuery .cookie and started typing. I was able to pull this off in only two functions. One to write the cookie and store the order in an arry, and the next to restore the order upon re-arrival.



/* SORTABLE LIST COOKIE */
var sortablelistSelector = "#sortablelist";
var sortablelistCookieName = "sortablelistCookie";
var sortablelistCookieExp = 365;
function sortablelistOrder() {
jQuery.cookie(sortablelistCookieName, jQuery(sortablelistSelector).sortable("toArray"), {expires: sortablelistCookieExp, path: "/"});
}
function sortablelistRestoreOrder() {
var i, previousorder, cookie = jQuery.cookie(sortablelistCookieName);
if (!cookie) { return; }
previousorder = cookie.split(',');
for (i = 0; i < previousorder.length; i++) {
jQuery('#'+previousorder[i]).appendTo(jQuery(sortablelistSelector));
}
}



/* SORTABLE COOKIE */
jQuery(sortablelistSelector).sortable({
cursor: "move",
update: function(){sortablelistOrder();}
});
sortablelistRestoreOrder();





<!--
<ul id="list1">
<li id="item-1">Spill</li>
<li id="item-2">Containment</li>
<li id="item-3">Solutions</li>
</ul>
-->









Published Fri. Mar. 15, 2013

Keywords: jQuery UI, .sortable, .cookie, .split(','), .appendTo, .length