Mára Toner Mára Toner - 7 months ago 55
Javascript Question

Jquery cookie - toggle box

I need to remember the state of clicked box (if its shown or hidden). I'm using cookies plugin for this.

When I click at

#clickable h3
I want to hide or reveal
#clickable p
... and I need to keep it hidden/revealed after F5 (so it will remember it's state).

On initial load that box must be hidden, but if no Javascript is present, it will be always revealed.

Here is my code:

$(document).ready(function(){
/* On load show/hide box depending on cookie */
if($.cookie('click_cookie') == true){
$.cookie('click_cookie', true);
$("#clickable p").show();
} else {
$.cookie('click_cookie', false);
$("#clickable p").hide();
}

/* When clicked */
$("#clickable h3").click(function(){
/* Animate box */
$("#clickable p").animate({
height: "toggle",
opacity: "toggle"
})
/* Toggle cookie */
if($.cookie('click_cookie') == true){
$.cookie('click_cookie', false);
} else {
$.cookie('click_cookie', true);
}
});
});


The problem is that it doesn't work as intended. The box is always hidden after F5.
$.cookie('click_cookie') == true
will never evaluate, so it will be always hidden.

Answer

Try this. $.cookie returns and sets strings:

$(function(){
  /* On load show/hide box depending on cookie */
  $("#clickable p").toggle($.cookie('click_cookie') == "true");

  /* When clicked */
  $("#clickable h3").click(function(){
    /* Animate box */
    $("#clickable p").animate({
        height: "toggle",
        opacity: "toggle"
    })
    /* Toggle cookie */
    var show = $.cookie('click_cookie') =="true"; // also false if no cookie at all
    $.cookie('click_cookie',show?"false":"true");
  });
});