JQuery - Remember Toggle State with Cookie
I have the following JQuery to toggle the header on my page. How can I use JQuery Cookie to remember the toggle state?
$(document).ready(function() {
$('#btnToggleHeader').click(function() {
$('#Header').slideToggle('slow');
});
});
Thank you very m开发者_StackOverflowuch!
A good resource regarding javascript and cookies is http://www.w3schools.com/JS/js_cookies.asp.
Based on this website we are given 3 functions: setCookie, getCookie and checkCookie (which gives us a demo of how to use the other two.)
To set the initial state of a toggle, something like this works:
$(document).ready(function(){
// The initial load event will try and pull the cookie to see if the toggle is "open"
var openToggle = getCookie("open") || false;
if ( openToggle )
$("#Header").show();
else
$("#Header").hide();
// The click handler will decide whether the toggle should "show"/"hide" and set the cookie.
$('#btnToggleHeader').click(function() {
var closed = $("#Header").is(":hidden");
if ( closed )
$("#Header").show();
else
$("#Header").hide();
setCookie("open", !closed, 365 );
});
});
Note: this is just a reference, I did not have time to test. Hope it helped.
Here is the final working version:
$(document).ready(function () {
$("#btnSearchToggle").click(function () {
var closed = $("#Header").is(":hidden");
if (closed)
$("#Header").show();
else
$("#Header").hide();
setCookie("open", closed, 365);
});
var openToggle = getCookie("open");
if (openToggle=="true") {
$("#Header").show();
}
else {
$("#Header").hide();
}
});
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
精彩评论