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

Get The Book of JavaScript, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.