Now, that was pretty simple -- but there's more than one way to skin a cat. If you're in a rush and don't have too much time to spend on implementing a custom cookie library, the Web throws up a number of interesting public-domain libraries which are powerful, stable and easy to use.
The best-known of these public-domain cookie libraries is the one created by Bill Dortch in 1996, and used extensively in many sites on account of its rich features and overall stability. Coincidentally, this is also the library I plan to use throughout the rest of this tutorial, so drop by and download a copy before reading any further.
// calculate expiry date 1 hour from now var d = new Date(); d.setTime(d.getTime() + (60 * 60 * 1000));
// write value to cookie SetCookie("username", user, d); alert("Data written successfully"); } </script> </head>
With the Bill Dortch library, setting a cookie is as simple as calling the SetCookie() function with appropriate arguments. The first two of these arguments are the mandatory name and value parameters - these must be set for the cookie to be valid. For persistent cookies, you would also follow these two arguments with an expiry date set to 60 minutes ahead of current time (60 minutes * 60 seconds * 1000 milliseconds); this will ensure that the cookie is saved to the hard drive and remains valid for 1 hour. For non-persistent (session) cookies, simply omit this expiry date.
Here too, once you've entered your name into the form and hit the "Save!" button, your cookie will be saved to disk in your browser's cookies directory. If you look at the code for the SetCookie() function, you'll see that internally, it does pretty much the same thing you manually did in the example on the previous page.