JQuery UI Sortable and Cookie

I must admit that I am very new to jQuery, although I want to somehow make this work.

I have igoogle style content with sortable widgets with this code

HTML

<div class="column">
    <div class="box">
        <div class="box-header">
            Header Widget
        </div>
                  <div class="box-content">
            <p>
            Content widget
            </p>
               </div>
        </div>
</div>


<div class="column">
        <div class="box">
            <div class="box-header">
                Header Widget
            </div>
                      <div class="box-content">
                <p>
                Content widget
                </p>
                   </div>
            </div>
    </div>

JQuery

$(".column").sortable({
        connectWith: '.column',
        handle: '.box-header',
        revert: 500
    });

How do I get this working with the cookie plugin?

Thanks for your time and help.

+3
source share
6 answers

First, download the cookie plugin (if you haven’t already): http://plugins.jquery.com/project/cookie

Next, read this short article that explains how to use the plug-in: http://www.electrictoolbox.com/jquery-cookies/

, , , , , . , onReady, - .

, , , , :

$(".column").sortable({
  connectWith: '.column',
  handle: '.box-header',
  revert: 500
  update: function(event, ui) {
    // This will trigger after a sort is completed
    var ordering = "";
    var $columns = $(".column");
    $columns.each(function() {
      ordering += this.id + "=" + $columns.index(this) + ";";
    });
    $.cookie("ordering", ordering);
  }
});

:

$(function() {
  var ordering = $.cookie("ordering");
  var orderings = ordering.split(";");
  $.each(orderings, function(index, ordering) {
    // Use each ordering, which will be in the form of "someId=someIndex" to actually
    // sort your stuff.  Not super-familiar with the Sortable package so you'll have to look
    // this part up on your own ... or just use basic jQuery stuff
  };
});

, .

+2

var setSelector = "#list1";
var setCookieName = "listOrder";
var setCookieExpiry = 7;


// function that writes the list order to a cookie
function getOrder() {
    // save custom order to cookie
    $.cookie(setCookieName, $(setSelector).sortable("toArray"), { expires: setCookieExpiry, path: "/" });
}

// function that restores the list order from a cookie
function restoreOrder() {
    var list = $(setSelector);
    if (list == null) return

    // fetch the cookie value (saved order)
    var cookie = $.cookie(setCookieName);
    if (!cookie) return;

    // make array from saved order
    var IDs = cookie.split(",");

    // fetch current order
    var items = list.sortable("toArray");

    // make array from current order
    var rebuild = new Array();
    for ( var v=0, len=items.length; v<len;>
        rebuild[items[v]] = items[v];
    }

    for (var i = 0, n = IDs.length; i &lt; n; i++) {


        var itemID = IDs[i];

        if (itemID in rebuild) {


            var item = rebuild[itemID];

            var child = $("ul.ui-sortable").children("#" + item);

            var savedOrd = $("ul.ui-sortable").children("#" + itemID);

            child.remove();

            $("ul.ui-sortable").filter(":first").append(savedOrd);
        }
    }
}

// code executed when the document loads
$(function() {

    $(setSelector).sortable({
        axis: "y",
        cursor: "move",
        update: function() { getOrder(); }
    });

    restoreOrder();
});

cookie

 Shopdev

+2

. . , , , ( JQuery-UI). .

$( ".ui-portlet" ).addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" );
$( ".ui-column .ui-portlet" ).find( ".ui-portlet-header" )
              .addClass( "ui-widget-header ui-corner-all" )
              .prepend( "<span class='ui-icon ui-icon-minusthick'></span>")
              .end()
      .find( ".ui-portlet-content" );
$( ".ui-portlet .ui-portlet-header .ui-icon" ).click(function() {
      $( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
      $( this ).parents( ".ui-portlet:first" ).find( ".ui-portlet-content" ).toggle("blind", "fast");
      return false;
});
$( ".ui-column" ).disableSelection();

Id (, ...).

$( ".ui-column" ).each(function(index, domEle){ $(domEle).attr('id', 'column_'+index)})
$( ".ui-column .ui-portlet" ).each(function(index, domEle){ $(domEle).attr('id', 'portlet_'+index)})

, , cookie .

$( ".ui-column" ).sortable({
      connectWith: ".ui-column",
      handle: '.ui-portlet-header',
      update: function(event, ui) {
          var cooked = new Array;
          $( ".ui-column" ).each(function(index, domEle){ cooked[index]= $(domEle).sortable('toArray')});
          $.cookie('cookie_name', cooked.join('|'), { expires: 7, path: '/'});
      }
});

restoreOrder.

function restoreOrder() {
    var cookie = $.cookie('cookie_name');
    if (!cookie) return;
    var SavedID = cookie.split('|');
    for ( var u=0, ul=SavedID.length; u &lt; ul; u++ ){ SavedID[u] = SavedID[u].split(',');}
    for (var Scolumn=0, n = SavedID.length; Scolumn &lt; n; Scolumn++) {
        for (var Sitem=0, m = SavedID[Scolumn].length; Sitem &lt; m; Sitem++) {
            $(".ui-column").eq(Scolumn).append($(".ui-column").children("#" + SavedID[Scolumn][Sitem]));
        }
    }
}
// TODO check why an empty column crash the loops !? Should not be complicate...

restoreOrder()

+1

. , ( , cookie).

$( ".ui-column" ).sortable({
      connectWith: ".ui-column",
      handle: '.ui-portlet-header',
      update: function(event, ui) {
          var cooked = new Array;
          $( ".ui-column" ).each(function(index, domEle){ cooked[index]= $(domEle).sortable('toArray')});
          $.cookie('cookie_name', 'x'+cooked.join('|'), { expires: 7, path: '/'});
      }
});
+1

, ,

function saveOrder() {
    var cookieName = "order";
     $.cookie(cookieName, $(".column").each(function(){ $(this).sortable("toArray")}));
    }

$(".column").sortable({
    connectWith: '.column',
        handle: '.box-header',
        revert: 500,
        update: function(event, ui) {
        saveOrder();

  }

, cookie?

0

Here is an example that localStorage uses to save an order. See Example: Elements need an identifier first. This identifier will be saved and used when restoring the order.

Demo: http://jsfiddle.net/bartburkhardt/2wgnsc2v

      $(function() {

        //add id to the li elements so after sorting we can save the order in localstorage
        $( "#sortable>li" ).each(function(index, domEle){ $(domEle).attr('id', 'item_'+index)});

        $( "#sortable" ).sortable({
          placeholder: "ui-state-highlight",
          update: function(event, ui) {        
            localStorage.setItem("sorted",  $("#sortable").sortable("toArray") );
          }
        });

        restoreSorted();

      });


      function restoreSorted(){

          var sorted = localStorage["sorted"];      
          if(sorted == undefined) return;

          var elements = $("#sortable");
          var sortedArr = sorted.split(",");

          for (var i = 0; i < sortedArr.length; i++){
              var el = elements.find("#" + sortedArr[i]);
              $("#sortable").append(el);
          };

      }

<ul id="sortable">
  <li class="ui-state-default">block 1</li>
  <li class="ui-state-default">block 2</li>
  <li class="ui-state-default">block 3</li>
  <li class="ui-state-default">block 4</li>
  <li class="ui-state-default">block 5</li>
  <li class="ui-state-default">block 6</li>
  <li class="ui-state-default">block 7</li>
  <li class="ui-state-default">block 8</li>
  <li class="ui-state-default">block 9</li>
  <li class="ui-state-default">block 10</li>
  <li class="ui-state-default">block 11</li>
  <li class="ui-state-default">block 12</li>
</ul>
0
source

Source: https://habr.com/ru/post/1716736/


All Articles