How to save jquery tab sorting and accordion order using cookies?

I have some jQuery sortable tabs and accordions that I want them to be in the same order whenever the user retrieves this page. I was thinking about using cookies for this.

How can i do this?

Thanks in advance.

+3
source share
1 answer

To make setting and getting cookies easier, use this jquery function:

// COOKIES!
// setting: $.cookie('name', value [, int]); // optional expiry in days
// getting: $.cookie('name');
// deleting: $.cookie('name', null);
$.cookie = function() {
  function get(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for (var i=0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }

  function set(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    } else {var expires = "";}

    document.cookie = name+"="+value+expires+"; path=/";
  }

  function xdelete(name) {
    set(name, null, -1);
  }

  if (arguments.length == 1) {
    return get(arguments[0]);

  } else if (arguments[1] == null) {
    xdelete(arguments[0]);

  } else {
    set(arguments[0], arguments[1], arguments[2]);
  }
}  

then set up a sorting handler on your sortable tabs (assuming you use jquery UI sorting):

$('.sortable').bind('sortchange', function() {
    // serialize the sort order (http://jqueryui.com/demos/sortable/#method-serialize)
    var sortable_order = $(this).sortable('serialize');
    // now you have a query string containing your item ids and their position
    // you can save them to a cookie and then do something with it next time the page loads
    $.cookie('sortable_order', sortable_order);

    // or you can send the sortable_order back to the server and save their order so that 
    // they can be rendered in the new order. This bypasses the need for cookies
    $.post('/your_item_sort_route_here', sortable_order);
    // of course you'd have to write your own backend logic for this
});

cookie, cookie sortable_order

$(document).ready(function() {
    var sortable_order = $.cookie('sortable_order');

    if (sortable_order) {
        // you would parse the sortable_order string to get the sortable item ids and their positions
        // and then use jQuery manipulation functions to rearrange the DOM
        // I'll leave that up to you! tee hee. If you can't figure this part out post back
        // and i'll give it a shot.
    }
});

, !

+1

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


All Articles