Make your own free website on
Cookies are perhaps the most advanced feature of javascript, at least in terms of understanding how they work. With cookies your page remembers your visitors and what they did while they were at your page.

The basic structure of setting a cookie should seem familiar, to change the value of the cookie, just rewrite it with the same structure but remember, if you change the name you are adding a new cookie and the old cookie will stay:

yourcookie = "some stuff";
document.cookie = "nameofthecookie="+escape(yourcookie)

The escape() method gets around the rule that cookies can't have spaces or punctuation, it is a built-in method which converts everything into ampersand characters - a space will look like & sp. To turn the gobbledygook back into readable sentences you will use unescape(). As you can see this is already a little funkier than the rest of javascript, read on it gets worse!

All the cookies made on the server will be displayed when you use the code


Since most personal homepage servers seem to set a cookie when you visit (used for hit-counters, etc), you will have to sort your cookie out from the rest. There are many "cookie scripts" available on the web. You can find one I wrote here

Annoyed? read on

So far, the cookies you have been making are "session" cookies. They disappear when you shut your box off - or close your browser window if you are using a computer. To make a "saved state" cookie you have to add an expiration date. You can't see the expiration date when you display the cookie but your box knows and will delete it around the time specified. To save a cookie with an expiration date:
exp = new Date();
days=2 // or any number of days you prefer;
expiredate = exp.setTime(exp.getTime()+1000*60*60*24*days);
yourcookie = "some stuff"
document.cookie = "nameofthecookie="+escape(yourcookie)+"; expires="+expiredate.toGMTString()

PS Don't escape the expires statement, _big_ mistake.

By now you must be thinking there must be a simpler way but there isn't. The routines may vary but the basics remain the same. Cookies are a pain.

A Final Word
There are a limitations on how many cookies you can have and how big each one can be so use them only you really need to.