O'Reilly logo

The Book of JavaScript, 2nd Edition by thau!

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Working with Cookies

This section covers all the basic cookie operations: setting, reading, and resetting cookies, and setting expiration dates.

Setting Cookies

Setting a basic cookie is simple. Create a string in the form cookie_name = value and then set the document.cookie property to that string. The only trick is that cookie values can't include spaces, commas, or semicolons. Happily, the escape() and unescape() functions will code and decode cookies, so you don't have to worry about this restriction.

Figure 12-3 lists a simple example that stores a visitor's name in a cookie named username.

The first line of the function in Figure 12-3 (❶) asks for a visitor's name and saves it in the_name. Line ❷ creates the string to store in the cookie. The ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required