jQuery UI Sortable list with cookie


/ Published in: jQuery
Save to your folder(s)

include jQuery, jQuery ui and jQuery cookie plugin. Simple.


Copy this code and paste it in your HTML
  1. //placeholder
  2. <style type="text/css">
  3. .ui-sortable-placeholder { border: 1px dotted #999;background:#f4f4f4; visibility: visible !important; height: 100% !important; width:100%!important; }
  4. </style>
  5.  
  6. //markup
  7. <div id="side">
  8. <div id="item1">item1</div>
  9. <div id="item2">item2</div>
  10. </div>
  11.  
  12. //functions
  13. // set the list selector
  14. var setSelector = "div#side";
  15. // set the cookie name
  16. var setCookieName = "listOrder";
  17. // set the cookie expiry time (days):
  18. var setCookieExpiry = 7;
  19.  
  20. // function that writes the list order to a cookie
  21. function getOrder() {
  22. // save custom order to cookie
  23. $.cookie(setCookieName, $(setSelector).sortable("toArray"), { expires: setCookieExpiry, path: "/" });
  24. }
  25.  
  26. // function that restores the list order from a cookie
  27. function restoreOrder() {
  28. var list = $(setSelector);
  29. if (list == null) return
  30.  
  31. // fetch the cookie value (saved order)
  32. var cookie = $.cookie(setCookieName);
  33. if (!cookie) return;
  34.  
  35. // make array from saved order
  36. var IDs = cookie.split(",");
  37.  
  38. // fetch current order
  39. var items = list.sortable("toArray");
  40.  
  41. // make array from current order
  42. var rebuild = new Array();
  43. for ( var v=0, len=items.length; v<len; v++ ){
  44. rebuild[items[v]] = items[v];
  45. }
  46.  
  47. for (var i = 0, n = IDs.length; i < n; i++) {
  48.  
  49. // item id from saved order
  50. var itemID = IDs[i];
  51.  
  52. if (itemID in rebuild) {
  53.  
  54. // select item id from current order
  55. var item = rebuild[itemID];
  56.  
  57. // select the item according to current order
  58. var child = $("div#side.ui-sortable").children("#" + item);
  59.  
  60. // select the item according to the saved order
  61. var savedOrd = $("div#side.ui-sortable").children("#" + itemID);
  62.  
  63. // remove all the items
  64. child.remove();
  65.  
  66. // add the items in turn according to saved order
  67. // we need to filter here since the "ui-sortable"
  68. // class is applied to all ul elements and we
  69. // only want the very first! You can modify this
  70. // to support multiple lists - not tested!
  71. $("div#side.ui-sortable").filter(":first").append(savedOrd);
  72. }
  73. }
  74. }
  75.  
  76. jQuery(document).ready(function() {
  77. jQuery("div#side").sortable({axis: "y",
  78. cursor: "move",
  79. update: function() { getOrder(); }
  80. });
  81.  
  82. // here, we reload the saved order
  83. restoreOrder();
  84. });

URL: http://jqueryui.com/demos/sortable/#placeholder

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.