Jquery - save class state for multiple div #'s to a cookie?

前端 未结 2 379
情话喂你
情话喂你 2021-01-16 19:09

I\'m trying to replicate a UI effect as on http://mcfc.co.uk I have written a script that hides a div on click function and applies a class to a div with the #id correspondi

2条回答
  •  滥情空心
    2021-01-16 19:48

    I posted a demo of what I think you want here. Be sure to include the jQuery cookie plugin.

    Here is the HTML I used:

    Feeds
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit
    News
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit
    Extra
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit
    Other
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit
    Last
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit

    And the script:

    $(document).ready(function(){
     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();
      $("#content-footer div[name='" + pid + "']").addClass('add');
     })
    
     // Add Click functionality
     $('.portlet').click(function(){
      $(this).hide();
      $("#content-footer div[name=" + this.id + "]").addClass('add');
      updateCookie( $(this) );
     });
     $("#content-footer div").click(function(){
      $(this).toggleClass('add');
      var el = $("div#" + $(this).attr('name'));
      el.toggle();
      updateCookie( el );
     });
    
     // 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;
    }
    
    // Fix indexOf in IE
    if (!Array.prototype.indexOf) {
     Array.prototype.indexOf = function(obj, start) {
      for (var i = (start || 0), j = this.length; i < j; i++) {
       if (this[i] == obj) { return i; }
      }
      return -1;
     }
    }
    

    Update: Added "indexOf" prototype at the end of the script above to fix an IE bug

    Update #2: Added cookieExpires variable, use a number to set the number of days, set it as a date() to set an end date or "null" to set it as a session cookie.

提交回复
热议问题