Peter Lea
Peter Lea

Reputation: 1751

jQuery slideToggle & cookie

I have a page which is dynamically generated and uses slideToggle to open and close the hierarchical divs etc no problem. The only problem is, everytime I postback I have to generate the divs again and they lose their opened/closed state. They are always generated with the same unique ids.

I would like to use the cookie plugin to remember the states when I call my sltoggle function and then when the page reloads expand all the same divs. Heres what i've got so far...

    $(document).ready(function () 
    {
        $(".toggle-hide").hide();
        //something in here about opening the divs in the cookie
    });

    function sltoggle(eID) 
    {
        $("div[id$='" + eID + "']").slideToggle(600);
        //I think the below code is okay - I copied it from a working example ^^
        var divState = ($("div[id$='" + eID + "']").css('display') == 'block') ? 1 : 0;
        $.cookie("divState", state)
     } 

Upvotes: 0

Views: 484

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191739

Comment explanations inline.

function slToggle(eID) {
   var $div = $("div[id$='" + eDI + "']");
   //Get value of cookie or empty string
   //Cookie is list of eIDs that should be visible
   var cooks = $.cookie("divState") || '';

   //Determine whether eID is already in the cookie
   var isin = $.inArray(eID, cooks.split(','));

   //TODO verify that .is("visible") check works during
   //toggle animation.  Otherwise, this code goes in the
   //toggle animation callback function
   if ($div.slideToggle(600).is(":visible")) {
      //Div is visible, but not in cookie
      if (!isin) {
         $.cookie("divState", cooks + (cooks ? ',' : '') + eID);
      }
   }
   else if (isin) {
      //Div not visible, but in cookie
      $.cookie("divState", cooks.replace(/(^|,)eID(,|$)/, ''));
   }
}

Upvotes: 1

Related Questions