I have successfully coded the following behaviour:
- Three divs are hidden/shown with .toggle();
- When the user uses the .toggle(); it also sets a cookie remembering the toggle state
Here is the jQuery of the code above, which works, with comments:
<script>
$(document).ready(function () {
// If user clicks the toggle it hides/shows the divs
$(" .togglediv ").click(function () {
var closed = $(" .siemaholder, .c_l_off, .c_r_off ").is(":hidden");
if (closed)
$(" .siemaholder, .c_l_off, .c_r_off ").show();
else
$(" .siemaholder, .c_l_off, .c_r_off ").hide();
// If user uses the toggle it sets a cookie to remember the toggle state
setCookie("open", closed, 365);
});
var openToggle = getCookie("open");
if (openToggle=="true") {
$(" .siemaholder, .c_l_off, .c_r_off ").show();
}
else {
$(" .siemaholder, .c_l_off, .c_r_off ").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);
}
}
}
</script>
The problem I have is that when no cookie exists yet (when the user visits the page for the first time and has not generated any cookies yet), the divs are hidden by default. I don't want this - I want them to be shown by default.
My intention is to show them by default, until a cookie is set by using the .toggle(); that I mentioned earlier. So that when the user first visits the page the content is showing and can then be 'hidden' by the user manually (which is remembered from there on).
Could anyone help me out?
So far I have tried using $(" .siemaholder, .c_l_off, .c_r_off ").show();
at the beginning of the script, so that by default the divs will be shown until cookies get involved. This didn't work.