Whether you like them or not, cookies are an easy way store simple user specific information across web pages and sessions. Here are the basic JavaScript methods to create (and update), read, or delete (CRUD) cookies with JavaScript.
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else {
var expires = ";";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var cookies = document.cookie.split(';');
for(var i = 0; i < cookies.length;i++) {
var cookie = cookies[i];
while (cookie.charAt(0) == ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) == 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Detailed explanation of code how this code works is available here. This script was originally written by Scott Andrew.
steve,
ReplyDeleteare you sure your javascript cookie code works in IE7? i'm teaching myself JavaScript and can't create a cookie in IE7, although i did succeed in IE6 but on a different machine.
thanks,
John K
wish i could make my earlier comment disappear. turns out i did make a cookie, but i missed seeing it because there were so many other cookies in my temporary internet files folder.
ReplyDeletethis code didnt work on IE7 =/
ReplyDeleteThat may be because I somehow introduced a typo in the code. (I had "var cokkies" instead of "var cookies" in the readCookie function.
ReplyDeleteI have corrected it now.
var expires = "";
ReplyDeleteshould be
var expires = ";";
Thank you for the correction.
ReplyDeleteThe code above is still buggy: in function readCookie there is a closing curly bracket missing after the following line:
ReplyDeletecookie = cookie.substring(1, cookie.length);
Thanks for the correction!
ReplyDeletePer the update at the top of this posting, I don't actually use this version anymore, but use the Flash storage enabled version. which had this correction, but I still want to keep the information provided here correct.