Here is the method I use:
var cookieHandler = {
"create": function(cookieName, value, daysToExpire) {
if (typeof daysToExpire !== 'number' || typeof cookieName !== 'string' || typeof value !== 'string') {
return false;
}
var expirationDate = new Date();
expirationDate.setTime(expirationDate.getTime() + (daysToExpire*86400000));
document.cookie = cookieName + '=' + value + '; expires=' + expirationDate.toGMTString() + '; path=/';
},
"read": function(cookieName) {
var allCookies = document.cookie,
index, val = false;
allCookies = allCookies.split(';');
for (index = 0; index < allCookies.length; index++) {
if (allCookies[index].indexOf(cookieName) !== -1) {
while (allCookies[index].indexOf(cookieName) > 0 && allCookies[index].length > cookieName.length) {
allCookies[index] = allCookies[index].substr(1);
}
val = allCookies[index].substr(cookieName.length + 1);
}
}
return val;
},
"erase": function(cookieName) {
this.create(cookieName, '', -1);
}
};
You can then use these methods:
cookieHandler.create("userName", "Bill", 7); // store userName "Bill" for 7 days.
cookieHandler.read("userName"); // "Bill"
cookieHandler.erase("userName");
Check out this code in action by visiting: http://jsfiddle.net/robert/4vLT6/