Reputation: 2201
I just wrote this code to use a slide to toggle a box as hidden/displayed using a button:
jQuery("#button").click(function () {
jQuery('#box').slideToggle('fast');
});
I want to implement cookies on this to remember if the box was hidden or visible. Can someone guide me with this?
Upvotes: 1
Views: 313
Reputation: 2201
I just got it working. I made two buttons so that there is different button on each state (i.e closed and open)
jQuery('#button_open').hide(); //initially we keep the open button hidden
// this code defines what happens when we click the close button
jQuery('#button_close').click(function () {
jQuery(this).hide(); //this hides the close button as the box is now closed
jQuery('#box').slideUp('fast'); //hides the box
jQuery('#button_open').show(); //shows the open button
jQuery.cookie("openclose","closed", {expires: 365}); // sets cookie
return false;
});
// this code defines what happens when we click the open button
jQuery("#button_open").click(function () {
jQuery(this).hide(); //hides the open button as the box is now open
jQuery('#box').slideDown('fast'); //shows the box
jQuery('#button_close').show(); //shows the close button
jQuery.cookie("openclose","open", {expires: 365}); //sets cookie
return false;
});
//and now the magical part comes in. this code checks if the cookie named 'openclose' has the value 'closed'. If yes, it hides the close button + the box and shows the open button.
if(jQuery.cookie("openclose") == "closed") {
jQuery("#button_close").hide();
jQuery("#button_open").show();
jQuery('#box').hide();
};
Upvotes: 1
Reputation: 34038
There is a jQuery Cookie plugin available, which will make reading and writing to and from cookies a lot easier and more convenient. Here is an example:
// if the slider is visible, set the cookie slider value to true
$.cookie('slider', 'visible', { expires: 7, path: '/' });
To read the value, use the following as an example:
var sliderVisible = $.cookie('slider');
More information can be found on the jQuery Cookies Plugin Site.
Upvotes: 3