jQuery UI portlets - toggle portlets to save to a cookie (half way there!)

Posted by Gareth on Stack Overflow See other posts from Stack Overflow or by Gareth
Published on 2010-04-15T16:10:23Z Indexed on 2010/04/15 16:13 UTC
Read the original article Hit count: 601

Filed under:
|
|

Hi,

I'm a bit of a jQuery n00b so please excuse me if this seems like a stupid question. I am creating a site using the jQuery UI more specifically the sortable portlets. I have been able store whether or not a portlet is has been open or closed to a cookie. This is done using the following code. The slider ID is currently where the controls are stored to turn each portlet on and off.

     var cookie = $.cookie("hidden");
 var hidden = cookie ? cookie.split("|").getUnique() : [];
 var cookieExpires = 7; // cookie expires in 7 days, or set this as a date object to specify a date

 // Remember content that was hidden
 $.each( hidden, function(){
  var pid = this; //parseInt(this,10);
  $('#' + pid).hide();
  $("#slider div[name='" + pid + "']").addClass('add');
 })

 // Add Click functionality

 $("#slider div").click(function(){
  $(this).toggleClass('add');
  var el = $("div#" + $(this).attr('name'));
  el.toggle();
  updateCookie(el);
 });

 $('a.toggle').click(function(){
    $(this).parents(".portlet").hide();
    // *** Below line just needs to select the correct 'id' and insert as selector i.e ('#slider div#block-1') and then update cookie! ***
    $('#slider div').addClass('add');
 });

 // Update the Cookie
 function updateCookie(el){
  var indx = el.attr('id');
  var tmp = hidden.getUnique();
  if (el.is(':hidden')) {
   // add index of widget to hidden list
   tmp.push(indx);
  } else {
   // remove element id from the list
   tmp.splice( tmp.indexOf(indx) , 1);
  }
  hidden = tmp.getUnique();
  $.cookie("hidden", hidden.join('|'), { expires: cookieExpires } );
 }
}) 

// Return a unique array.
Array.prototype.getUnique = function() {
 var o = new Object();
 var i, e;
 for (i = 0; e = this[i]; i++) {o[e] = 1};
 var a = new Array();
 for (e in o) {a.push (e)};
 return a;
}

What I would like to do is also add a [x] into the corner of each portlet to give the user another way of hiding it but I'm unable to currently get this to store within the Cookie using the code above.

Can anyone give me a pointer of how I would do this?

Thanks in advance!

Gareth

© Stack Overflow or respective owner

Related posts about jquery-ui

Related posts about cookies