开发者

jquery and cookie status

What i'm trying to do is have a sidebar toggle open and close which is working fine but I also want cookie to remember the sidebar state when browsing site and when returning to page its on

ie: if closed be closed if open be open:

$(document).ready(function($) {
 $('a#side').click(function(){
  $('#sidebar').toggle();
$('a#side').text($(this).text() == 'Show' ? 'Hide' : 'Show');
  $.cookie('side_cookie', 'value');
 return false;
});
if($.cookie('side_cookie')) { 
$('#sidebar').hide(); 
   } else {
$('#sidebar').show();
   }
});

The current code above just remembers if its been closed and stays closed until session is ended and so you have to toggle it open each time you return to page ...

An example of what im trying to achieve can be seen at vbulletin.com/forum/ if you close their sidebar then browse the开发者_JAVA百科 forums when you go back to main page its still closed and visa versa.

any help is appreciated


I think the issue is with if condition if($.cookie('side_cookie')). Try this:

$(document).ready(function($) {
 $('a#side').click(function(){
  $('#sidebar').toggle();
$('a#side').text($(this).text() == 'Show' ? 'Hide' : 'Show');
  $.cookie('side_cookie', $(this).text());
 return false;
});
if($.cookie('side_cookie')=='Hide') { 
$('#sidebar').hide(); 
   } else {
$('#sidebar').show();
   }
});


You have to check the value of the cookie rather than its existence. Also you are hardcoding the value of the cookie as value. Change it to show or hide.

// when it is shown
$.cookie('side_cookie', 'show');

// when it is hidden

$.cookie('side_cookie', 'hide');

and check the value of the cookie

if($.cookie('side_cookie') === "show") {
    // code for showing side bar
}
else {
    // code for hiding the side bar
}


Ok thx guys but I got it sorted, its alot more code then I wanted as its alot of .show()/.hide() rather then .toggle() buts it works sofor now it will do:

$('a#hide').click(function(){
  $('a#hide,#sidebar').hide();
  $('a#show').show();
  $.cookie('side_cookie_hidden', 'hidden');
  $.cookie('side_cookie_show', null);
 return false;
});

$('a#show').click(function(){
  $('a#show').hide();
  $('a#hide,#sidebar').show();
  $.cookie('side_cookie_show', 'show');
  $.cookie('side_cookie_hidden', null);
 return false;
});

if($.cookie('side_cookie_hidden')) { 
$('a#show').show();
$('a#hide,#sidebar').hide(); 
   } else {
$('a#show').hide();
$('a#hide,#sidebar').show(); 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜