Previous Page
Next Page

Baking Your First Cookie

A cookie is a text string with a particular format:

cookieName=cookieValue; expires= expirationDateGMT; path=URLpath; domain=siteDomain

Breaking this down, the first part of the string gives the cookie a name and assigns it a value. This is the only mandatory part of a cookie; the rest of the string is optional. Next is the expiration date of the cookie; when this date is reached, the browser automatically deletes the cookie. The expiration date is followed by a URL path, which lets you store a URL in the cookie. Finally, you can store a domain value in the cookie.

Script 10.1, the HTML file, calls the JavaScript in Script 10.2, which sets a cookie from a value entered by the user into a form. When you try this one out, it won't appear to do that much (as in Figure 10.1), but the cookie is actually being created. Later examples in this chapter build on this one.

Script 10.1. The HTML for our first cookie page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="">
     <title>Set a cookie based on a form</title>
     <script language="Javascript"  type="text/javascript"  src="script01.js">
<body bgcolor="#FFFFFF">
     <form action="#">
        <h1>Enter your name: <input type="text" id="nameField" /></h1>

Script 10.2. Use this script to set a browser cookie.

window.onload = nameFieldInit;

function nameFieldInit() {
     var userName = "";
     if (document.cookie != "") {
        userName = document.cookie.split ("=")[1];

     document.getElementById("nameField"). value = userName;
     document.getElementById("nameField"). onblur = setCookie;

function setCookie() {
     var expireDate = new Date();
     expireDate.setMonth(expireDate. getMonth()+6);

     var userName = document.getElementById ("nameField").value;
     document.cookie = "userName=" + userName + ";expires=" + expireDate.toGMTString();

Figure 10.1. It doesn't look like much, but the content of the form's text field has just been written to a cookie.

To set a cookie:

function nameFieldInit() {

First, set up the function nameFieldInit() to define the value of the cookie. This function is called when the window has completed loading.

var userName = "";

Next, we initialize the variable userName with a null value.

if (document.cookie != "") {
  userName = document.cookie. split("=")[1];

We begin a conditional test by first checking that the object document.cookie does not contain a null value. The method split("=") splits a cookie into an array, where cookieField[0] is the cookie name and cookieField[1] is the cookie value. Note that cookieField can be any variable that you want to use to store a particular cookie's fields. So you assign userName the value returned by document.cookie.split("=")[1], that is, the cookie value.

document.getElementById("nameField") .value = userName;

Setting getElementById("nameField").value puts the user's name into the text field when the page loads if there's a name stored in the cookie file.

document.getElementById("nameField") .onblur = setCookie;

The onblur event handler (see Chapter 1) calls the setCookie() function when the user leaves the text field.

function setCookie() {

Now begin a new function, called setCookie().

var expireDate = new Date();

Get the current date, and put it into the new variable expireDate.

expireDate.setMonth(expireDate. getMonth()+6);

This line gets the month portion of expireDate, adds 6 to the month, and then sets the month portion of expireDate to the new value. In other words, it sets the expiration date of the cookie we're creating to six months in the future.

var userName = document.getElementById("nameField").value;

This line creates a new userName variable and assigns it whatever the user typed into the text field. The userName variable has to be created twice (once inside each function) because it's not a global; that is, we're using it inside each function, but we're not expecting it to keep its value across functionsit's new each time.

document.cookie = "userName=" + userName + ";expires=" + expireDate.toGMTString();

Here's where we write the cookie. We're setting document.cookie (remember, a cookie is just a text string, so you can use the same text string techniques to build it, like using the + sign to combine things) to contain the user's name and the cookie expiration date. The toGMTString() method converts the expireDate Date object into a text string so that it can be written into the cookie.

A Fistful of Cookies

You can have multiple cookies on a page, and the format for this is:

"cookieName1=cookieValue1; expires1=expirationDateGMT1;
 path1=sitePath1; domain1=siteDomain1"; "cookieName2=cookieValue2;
 expires2=expirationDateGMT2; path2=sitePath2; domain2=siteDomain2"

Again, the only mandatory fields are the name and value pair.

The split("; ") command splits the multiple cookie record into an array, with each cookie in a cookie record numbered from 0 on. Note that there is a space after the semicolon in this command. So cookieArray[0] would be the first cookie in the multiple cookie record, cookieArray[1] would be next, and so on. For more, see the "Handling Multiple Cookies" example later in this chapter.


  • This script assumes that the first cookie contains the user name. Later scripts show how to handle multiple cookies and get a cookie by name instead of number.

  • The scripts in this chapter are ordered in such a way that they'll work fine if you run them in the order they appear. If you skip around, though, you may encounter some weird results (such as the browser thinking that your name is a number). If you want to run them out of sequence, try running Script 10.7 ("Deleting Cookies") in between scripts.

Previous Page
Next Page