Sams Teach Yourself JavaScript in 24 Hours
- Table of Contents
- Copyright
- About the Author
- Acknowledgments
- We Want to Hear from You!
- Reader Services
- Introduction
- Part I: Getting Started
- Hour 1. Understanding JavaScript
- Hour 2. Creating a Simple Script
- Hour 3. How JavaScript Programs Work
- Part II: Learning JavaScript Basics
- Hour 4. Using Functions and Variables
- Hour 5. Using Strings and Arrays
- Hour 6. Testing and Comparing Values
- Hour 7. Repeating Yourself: Using Loops
- Hour 8. Using Math and Date Functions
- Part III: The Document Object Model (DOM)
- Hour 9. Working with the Document Object Model
- Hour 10. Responding to Events
- Hour 11. Using Windows and Frames
- Hour 12. Getting Data with Forms
- Hour 13. Using Graphics and Animation
- Part IV: Moving on to Advanced JavaScript Features
- Hour 14. Creating Cross-Browser Scripts
- Hour 15. Creating Custom Objects
- Hour 16. Working with Sounds and Plug-Ins
- Hour 17. Debugging JavaScript Applications
- Part V: Working with Dynamic HTML (DHTML)
- Hour 18. Working with Style Sheets
- Hour 19. Using Dynamic HTML (DHTML)
- Hour 20. Using Advanced DOM Features
- Part VI: Putting It All Together
- Hour 21. Improving a Web Page with JavaScript
- Hour 22. Creating a JavaScript Game
- Hour 23. Creating DHTML Applications
- Hour 24. JavaScript Tips and Tricks
- Part VII: Appendices
- Appendix A. Other JavaScript Resources
- Appendix B. Tools for JavaScript Developers
- Appendix C. Glossary
- Appendix D. JavaScript Quick Reference
- Appendix E. DOM Quick Reference
Workshop: Using Cookies
You've learned quite a bit in your 24-hour exploration of JavaScript. Just to prove that there's more to learn if you choose, here's a final lesson on a useful JavaScript feature for advanced scripts.
Cookies allow you to store one or more variables on the user's computer. This allows your Web pages to remember key information—for example, a username or the current score in an online game.
Unlike regular JavaScript variables, cookies are persistent—once you've set one, it will be available to your script each time the same user views your page until the cookie reaches the expiration date you've set. They're a great way to recognize previous visitors or to let the user avoid typing the same information over and over.
Setting a Cookie
Cookies are specific to a single Web page. You can set one or more cookies using the document.cookie property. To set a cookie, you just need to specify a name for the cookie, a value, and an expiration date:
name=window.prompt("Please enter your name","");
d = new Date();
d.setFullYear(d.getFullYear() + 1);
expires="expires=" + d.toGMTString();
document.cookie="Username=" + name + "; " + expires;
This example prompts for a name and sets a cookie called Username to store the name. The d variable is used to store the expiration date, which is set one year in the future. If the user name is Fred, the cookie value will look something like this:
Username=Fred; expires= Fri, 25 Apr 2004 08:14:05 UTC
To delete a cookie, you simply re-set it using an expiration date in the past. You can also set an existing cookie to a new value.
Reading a Cookie
As you might have guessed, reading a cookie is as simple as reading the document.cookie property. However, this property includes all the cookies for the current page—since there might be more than one, you need to use some string functions to extract the cookie you want. The following example finds the Username cookie's value:
cookies=document.cookie;
startpos=cookies.indexOf("Username") + 9;
endpos=cookies.indexOf("",startpos);
if (endpos==-1) endpos=cookies.length;
name=cookies.substring(startpos,endpos);
This code uses the indexOf method to find the position of the Username= string that begins the cookie. It adds nine characters to skip over Username=, and this is the start position of the value.
The end position is calculated by looking for a semicolon after the start position. Some browsers don't include the semicolon when there's only one cookie, so it sets the end position to the end of the document.cookie value if there isn't a semicolon.
Having calculated the start and end positions for the value, the final line of this example uses the substring method to read the value for the Username cookie.
Putting It All Together
Now that you've learned how to set a cookie and how to read the value of a cookie, you can put them together to make a simple example. This example displays a personalized welcome message when it loads. The first time you load it, it prompts for a name and stores the name in a cookie.
The second time you load this example, it uses the name stored in the cookie and doesn't need to prompt for a name. Listing 24.1 shows the complete example.
Example 24.1. Complete Cookie Personalized Welcome Message
<html>
<head><title>Cookie Example</title>
</head>
<body>
<h1> Cookie Example</h1>
<script language="javascript1.1" type="text/javascript1.1">
cookies=document.cookie;
startpos=cookies.indexOf("Username") + 9;
if (startpos<9) {
// No cookie set
name=window.prompt("Please enter your name","");
d = new Date();
d.setFullYear(d.getFullYear() + 1);
expires="expires=" + d.toGMTString();
document.cookie="Username=" + name + "; " + expires;
document.write("<h2>Welcome, " + name + "!</h2>");
} else {
// Cookie was found
endpos=cookies.indexOf("",startpos);
if (endpos==-1) endpos=cookies.length;
name=cookies.substring(startpos,endpos);
document.write("<h2>Welcome Back, " + name + "!</h2>");
}
</script>
<p>This example's script uses a cookie to save
the user name. If no cookie is set, it prompts for
a name.</p>
</body>
</html>
To test this example, load it into a browser—it should work with Netscape 4 or later or Internet Explorer 4 or later. You'll be prompted for a name, and the next time you load the page it will welcome you back using the name stored in the document's cookie. Figure 24.1 shows the example in action.
Figure 24.1 The cookie example in action.
Summary | Next Section

Account Sign In
View your cart