Thursday, October 05, 2006

Using Cookies in JavaScript

Update (February 23, 2007): I have updated the cookies functionality below to utilize flash storage if available and fall back to cookies if not available. See Cookies and Flash for local storage

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.

8 comments:

yitwail said...

steve,

are 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

yitwail said...

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.

mueller said...

this code didnt work on IE7 =/

Steven Pothoven said...

That may be because I somehow introduced a typo in the code. (I had "var cokkies" instead of "var cookies" in the readCookie function.

I have corrected it now.

Anonymous said...

var expires = "";
should be
var expires = ";";

Steven Pothoven said...

Thank you for the correction.

chris said...

The code above is still buggy: in function readCookie there is a closing curly bracket missing after the following line:
cookie = cookie.substring(1, cookie.length);

Steven Pothoven said...

Thanks for the correction!

Per 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.