Reputation: 25
How do I set a cookie using jquery to remember which div is toggled and keep it toggled when the page is refreshed?
I have have tried many solutions and almost have it figured out, but I'm getting stuck when setting and retrieving the cookie.
My HTML:
<a href="javascript:showonlyone('newboxes2');" >Login</a>
<a href="javascript:showonlyone('newboxes3');" >Register</a>
<div class="newboxes" id="newboxes1" style="display: block">
default text to be shown when no cookies are set
</div>
<div class="newboxes" id="newboxes2" style="display: none">
login form
</div>
<div class="newboxes" id="newboxes3" style="display: none">
register form
</div>
My script:
/************jQuery Cookie**************/
;(function(g){g.cookie=function(h,b,a){if(1<arguments.length&&(!/Object/.test(Object.prototype.toString.call(b))||null===b||void 0===b)){a=g.extend({},a);
if(null===b||void 0===b)a.expires=-1;
if("number"===typeof a.expires){var d=a.expires,c=a.expires=new Date;
c.setDate(c.getDate()+d)}b=""+b;
return document.cookie=[encodeURIComponent(h),"=",a.raw?b:encodeURIComponent(b),a.expires?";
expires="+a.expires.toUTCString():"",a.path?";
path="+a.path:"",a.domain?";
domain="+a.domain:"",a.secure?";
secure":
""].join("")}for(var a=b||{},d=a.raw?function(a){return a}:decodeURIComponent,c=document.cookie.split("; "),e=0,f;f=c[e]&&c[e].split("=");
e++)if(d(f[0])===h)return d(f[1]||"");
return null}})(jQuery);
if ($.cookie('showDiv') == 'newboxes2'){
newboxes2.show();
}
if ($.cookie('showDiv') == 'newboxes3'){
newboxes3.show();
}
function showonlyone(thechosenone) {
$('.newboxes').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).show(200);
$.cookie('showDiv', thechosenone);
}
else {
$(this).hide(600);
}
});
}
If the cookie code isn't formatted properly, there is a working example here: http://jsfiddle.net/CQFJ4/ but that fiddle doesn't do what I need, I just borrowed the cookie code.
The place I'm getting stuck is setting the cookie in the each loop using $(this) and then recalling that cookie when the page is refreshed Thanks for the help I really appreciate it!
Upvotes: 0
Views: 1201
Reputation: 700840
If you put this
inside a string, it won't be interpreted as an identifier, it will just be those four characters. You would need to concatenate the id from the element into the string, so this would work with your current code:
$.cookie($(this).attr('id') + '.showDiv', 'visible');
However, every cookie value is sent back an forth between the server and the browser in every request, and the space allowed for cookies for a domain is limited to a few kilobytes, so you should keep the cookies as small as possible. Use a single cookie and put the identify of the visible element in the value instead:
$.cookie('showDiv', thechosenone);
Then you check the value when displaying the elements:
if ($.cookie('showDiv') == 'newboxes2'){
newboxes2.show();
}
Upvotes: 1