Saving Cookies

Setting cookies is really easy as Example 16-2 shows.

Example 16-2. Setting a cookie
<html>
<head>
<title>cookies</title>

<script language="JavaScript">
document.cookie="test=my_test"
</script>

</head>
<body>
set the cookie
</body>
</html>

HOW THE CODE WORKS

Well, that's not too hard. There's only one cookie object in the document, so there's no confusion from adding to any sort of cookie array or cookie object. Using document.cookie simply adds “test=my_test” to the list of cookies in the browser memory.

But what if we want to save another cookie, like “pants=blue”? Easy.

<script language="JavaScript">
    document.cookie="test=my_test"
    document.cookie="pants=blue"
</script>

This code creates two cookies. The pants=blue cookie ...

Get Advanced JavaScript™: Insights and Innovative Techniques now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.