Understanding JavaScript Cookies
The word cookie is one of those technological terms where the name doe snothing to convery what the feature actaully does. It is commonly believed that even the people at Netscape responsible for devising and implementing cookies in JavaScript didn't really have a vlaid reason for selecting the name. Questionable naming aside, JavaScript cookies are actually an extremely powerful feature.
What is a JavaScript Cookie?
Cookies allow you to store information on the computer of the person browsing your site. Before you carried away with dreams of secretly storing all this music file and pictures clogging your hard drive on the disks of your site visitors you first need to understand some limitions. Firstly a cookie can only hold name/value pairs (i.e name=value settings). You cannot store binary or any sort of data in a cookie. Secondly a cookies can only be a maximum of 4kb in size each. Finally, a single server or domain can only store a total of 20 cookies per user browser.
Another common limitation of cookies is that browsers can be configure to turn off support for cookies. If you design a web site that relies on cookies being supppoted by the user's browser there is the possibility that your site will fail to function for a certain percentage of your visitors.
Despite the limitations outlined above cookies provide an excellent way to maintain state on the clients browser. For example you might want to store information in a cookie so that when a user returns to your site they can pick up where they left off (perhaps partway through completing a purchase in an online shopping cart).
Creating a Coookie
Cookies are created using the cookie property of the Document object. The format of a cookies is as follows:
name=value; expires=expirationDateGMT; path=URLpath; domain=siteDomain
The first section of the cookie defines the name of the cookie and the value assigned to the cookies. Both the name and value settings can be anything you choose to use. For example you might want save a user's currency preference - currency=USDollars. This is the only section of the cookie that is mandatory. The followingf settings can be omitted from the cookies if they are not requied.
The option expires= section specifies the date on which the cookie should expire. The JavaScript Date Object can be used to obtain and manipulate dates for this purpose.