Using cookies

One of the greatest limiting factors of HTML is the inability to store non-volatile information. For example, think of the address book example used a few sections back. The example prompted for names and phone numbers, and then displayed them back in HTML. However, once the browser loaded a new page, all the information was lost, which defeated the purpose of the address book. Using cookies, the pertinent phone numbers could be stored on the hard disk, and loaded on the next visit.

Cookie information is made available to JavaScript through the cookie property of the document object. Continuing with the previous example, suppose that we have already set two cookies to a document: one named 'Travis' with the value '9288-9110' and another named Ashton with the value set to '9288-9188'. We could view the document's cookies using the following line of code:

document.writeln(document.cookie);

Executing the command would produce the following line of text:

Travis=9288-9110; Ashton=9288-9188

Using the same logic, assigning a value to the cookie property adds a new cookie to the document. If we wanted to add a cookie for Nathan, we could use the following line of code:

document.cookie = "Nathan=9288-9175";

After assigning the new cookie value, the cookie string for the document would contain the following information:

Travis=9288-9110; Ashton=9288-9188; Nathan=9288-9175

Notice that the end of the string does not contain a semicolon. This will become important later when we retrieve cookie values.