Using Cookies in JavaScript

by Castwide on 2-19-2008 • Tags: code, cookies, javascript0 comments

Cookies can be a useful tool for storing small pieces of data like user preferences in rich web applications. JavaScript is able to access cookies through the Document.cookie object. Working with Document.cookie can be a little hairy, because it requires a specific format for setting values, and it returns the cookie as a delimited string. Fortunately, the details are very easy to hide with a couple of simple JavaScript functions.

I took the cookie handling functions from QuirksMode and made some small modifications to encapsulate them in a Cookie object. The complete code is as follows:


var Cookie = new function() {
this.get = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
this.set = function(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=/";
}
this.del = function(name) {
Cookie.set(name,"",-1);
}
}

This script provides three functions:

  • Cookie.get(name) - Get the value of a cookie by its name
  • Cookie.set(name, value, days) - Set the cookie's value and the number of days until it expires
  • Cookie.del(name) - Delete the cookie

You can see a demonstration of the code here. The demo lets you set a cookie's value from a form and displays the current value when you reload the page.

Download the source

There are no comments posted to this news item.

Add Comment

More Articles