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