Because cookies are persistent, that is, because they are available across multiple sessions between a Web server and browser, you can use cookies to store how many times a particular user has accessed a page. But this isn't the same thing as the page counters you see on many Web pages. Because a cookie is specific to a user , you can only tell that user how many times he or she has visited; you can't use cookies to tell all users how many times the page has been hit. Still, it's useful to know how to create such an individual counter, and you can adapt Script 10.6 for other purposes, too (see Tips).
1. | var expireDate = new Date(); expireDate.setMonth(expireDate. getMonth()+6); These two lines are the same as in steps 7 and 8 of the "Baking Your First Cookie" example. Refer there for an explanation. |
2. | var hitCt = parseInt(cookieVal ("pageHit")); The string pageHit is the name of the cookie. In a few steps, you'll see the function cookieVal() . This line takes the name of the cookie from cookieVal() , turns it into a number using the parseInt() method, and then stores the result in the variable hitCt . The parseInt() method changes a string (which is what is in the cookie) into a number (which is what the variable needs to use it as a counter). |
| |
3. | Now take the value of hitCt and add 1 to it, incrementing the counter. |
4. | document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate. toGMTString(); This writes back the updated information to the cookie for future use. What's being written is a text string that combines the string "pageHit=" with the incremented value of hitCt and adds ";expires=" with the expiration date, which was incremented by six months back in step 1. |
5. | [View full width] [View full width] document.getElementById("pageHits"). innerHTML = "You have visited this page " + hitCt + " times."; This line displays the user message in the document ( Figure 10.5 ). There are extra spaces after "page" and before "times" to make the line look right on screen. |
6. | function cookieVal(cookieName) { This line begins a new function called cookieVal() . It is passed some data, which can then be referenced inside the function as the variable cookieName . |
7. | var thisCookie = document.cookie. split("; "); The variable thisCookie is set to the array generated by the split("; ") method. |
8. | for (var i=0; i<thisCookie.length; i++) { Here we're beginning a loop, just as in step 4 of the "Showing Your Cookies" example. |
| |
9. | if (cookieName == thisCookie[i]. split("=")[0]) { This conditional checks to see if cookieName is the same as the i th element of the cookie array. |
10. | return thisCookie[i].split("=")[1]; If the test in step 9 succeeded, then return the cookie's value. |
11. | If we've looked at all the items in the array and found no match, return a 0 value. |