HTML and CSS Reference
In-Depth Information
EXAMPLE 16.2 ( CONTINUED )
<p>
11
<input type="button"
value=" Get Cookie" onClick="welcome(this.form); "/>
</p>
</form>
</div>
</body>
</html>
EXPLANATION
1
A function called makeCookie() is defined. It takes a reference to a form as its only
parameter. This is the function that creates the cookie.
2
A new Date object is created and assigned to the variable called when .
3
The Date object creates a date a year from now. This will be the expiration date for
the cookie.
4
Two cookies are created. The first cookie's name is “visitor” and its value is the us-
er's name, stored in yname . The second cookie's name is “color” and its value
stored in favcolor. Both values came from the form input. The attributes are es-
caped just in case the user added unwanted characters, such as spaces, commas,
or semicolons. The expiration date is set to a year from now and is converted to
GMT time, the required format for the “expires” attribute. Notice the quotes. If the
text is literal for the attribute it must be quoted; if it is a variable value, then it is
not quoted or JavaScript can't interpret it—very tricky getting these right.
5
A function called welcome() is created. It takes a reference to a form as its only
parameter. Its purpose is to greet the user based on the cookie value.
6
The following statements are used to parse out the value attribute of the cookie.
The beginning index position is set to where the “name=” string starts in the cook-
ie string. It will be at position 5 in this example. Starting at index position 0, po-
sition 5 takes us to the character directly after the = sign. The end position is ei-
ther at the first semicolon or at the end of the string, whichever applies.
7
After getting the substring, the value part of the cookie, the unescape() function,
will convert the URI-encoded string back into its original ASCII format.
8
The user is welcomed, all based on the value extracted from the cookie. The cook-
ie lets this Web site know who you are so that you can get a personal greeting
when you return to the site.
9
The user will enter his or her name in a textbox field. See Figure 16.8.
10
When the user clicks this button, the onClick event is triggered, and the cookie
will be made. See Figure 16.9.
11
When the user clicks this button, the onClick event is triggered, and the user will
be welcomed by the name he or she entered in the textbox. See Figure 16.10.
Search WWH ::




Custom Search