An exercise in learning the basics of JavaScript cookies. Cookies seemed like a subspecies in the JavaScript language, and I had avoided it for a long time mainly for two reasons: 1) It’s another syntax to learn, and 2) I don’t like that it stores personal information and I don’t want to use it for my website if it’s not absolutely necessary.
This experiment was carried out to figure out how to configure a function in the portfolio page.
11–14 Sept 2008.
Lots of troubleshooting and getting the right syntax. Different browsers seem to interpret slightly differently, so it’s somewhat hard to tell what’s happening, too.
Here’s the code. Please link back here if you’re using it.
Put this JavaScript in the head tag.
//The following functions contains parts that derives from the Cookies tutorial on quirksmode.org
function setCookie(name,value,days){
//if "days" is defined
if (days){
// create new date to be defined as number of days from now that the cookie will expire
var date=new Date();
// the math behind setting the date
date.setTime(date.getTime()+(days*24*60*60*1000));
// get a new var to hold the date in GMT format
var expires=date.toGMTString();
} else {
//if "days" isn't defined, just make "expires" nothing, so the cookie will expire right after the browser closes
var expires="";
}
//put the cookie together: name, value, expiration date
document.cookie=name+"="+escape(value)+"; expires="+expires;
}
Put this HTML in the body tag.
<div id='alertButton' >
Click to see the status of the switch.
</div>
<div id='switchButton' >
Click to switch.
</div>
<div id='clearCookieButton' >
Click to clear the cookie.
</div>
Place this JavaScript at the end of body tag, after the above HTML.
var alertButton=document.getElementById("alertButton");
alertButton.onclick=function(){
alert(genSwitchText("switchOn"));
}
var switchButton=document.getElementById("switchButton");
switchButton.innerHTML=genSwitchText("switchOn")+" Click to switch.";
switchButton.onclick=function(){
switchCookie("switchOn",1);
switchButton.innerHTML=genSwitchText("switchOn")+" Click to switch.";
}
var clearCookieButton=document.getElementById("clearCookieButton");
clearCookieButton.onclick=function(){
setCookie("switchOn","",-1);
switchButton.innerHTML=genSwitchText("switchOn")+" Click to switch.";
alert("Cookie cleared");
}