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.

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:

1.
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.

2.
var userName = "";



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

Script 10.1. The HTML for our first cookie page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Set a cookie based on a form</title>
     <script type="text/javascript" src="script01.js"></script>
</head>
<body bgcolor="#FFFFFF">
     <form id="cookieForm" action="#">
        <h1>Enter your name: <input type="text" id="nameField" /></h1>
     </form>
</body>
</html>

3.
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.

4.
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.

5.
document.getElementById("nameField").onblur = setCookie;
  document.getElementById("cookieForm").onsubmit = setCookie;



In the first line, the onblur event handler (see Chapter 1) calls the setCookie() function when the user leaves the text field. In the second, we do the same thing for the form’s onsubmit handler. If you press Enter after you’ve typed your name, Internet Explorer, for some reason, doesn’t trigger the onblur handler. Adding the onsubmit handler catches all the variants.

6.
function setCookie() {



Now begin a new function, called setCookie().

7.
var expireDate = new Date();



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

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;
							document.getElementById("cookieForm").onsubmit = 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();
							document.getElementById("nameField").blur();
							return false;
}

8.
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.

9.
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 functions—it’s new each time.

10.
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.

11.
document.getElementById("nameField").blur();
return false;



Remember when we set up the form so that setCookie() could be called in one of two ways? Here’s where we handle the fallout of that choice:

  • If we’re in IE, the first line causes the focus to leave the name field, so it’s clear that something has occurred, and the second (returning a value of false) keeps the form from actually submitting.

  • If we’re not in IE, the first line does nothing (that is, we’ve already left the name field, so leaving it again doesn’t matter) and the second line keeps the form submission from being triggered.

✓ Tips

  • 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.


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.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.192.79