• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Creating Cookies

One of the most powerful document object properties is the cookie property, which enables you to set and read cookies. We’ll see how to use cookies in Chapter 23, “Cookies and Creating Your Own Objects,” but here’s a preview. The cookie property holds the text of the cookies in the computer, so you give your cookie a name; I’ll just use cookie1 here, and give it an expiration date of one day. When the user clicks a button, the code will set a cookie with the text “Here is the cookie text.”, and when the user clicks another button, the code retrieves that cookie’s text and displays it. Here’s the code—see Chapter 23 for the details on working with cookies:

(Listing 09-03.html on the web site)

        <TITLE>Working With Cookies</TITLE> 
        <SCRIPT LANGUAGE="JavaScript"> 
            function setCookieText()
					var date1 = new Date()
					date1.setTime(date1.getTime() + 24 * 60 * 60 * 1000)
					document.cookie = "cookie1=Here is the cookie text.;expires="
					+ date1.toGMTString()
					function getCookieText()
					var cookieData = new String(document.cookie)
					var cookieHeader = "cookie1="
					var cookieStart = cookieData.indexOf(cookieHeader)
					if (cookieStart != -1){
					document.form1.text1.value = cookieData.substring(cookieStart
					+ cookieHeader.length)
					document.form1.text1.value = "Could not find the cookie."
            // --> 

        <H1>Working With Cookies</H1> 
        <FORM NAME="form1"> 
            <INPUT TYPE="TEXT" NAME="text1" SIZE="40"> 
            <INPUT TYPE="BUTTON" VALUE="Create a cookie" ONCLICK="setCookieText()"> 
            <INPUT TYPE = BUTTON Value = "Retrieve cookie data" 




Not a subscriber?

Start A Free Trial

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint