Normally cookies can only be accessed through CGI scripts. Information on doing this can be found on Netscape's Cookie Spec pages or, for a more Mac based spin, look at Andy's Cookie Pages.
In an environment where CGI scripts can't be used however there is another way...
Go ahead and re-load this page... see how the counter above updates? The count is being kept in a cookie that's being stored in your browser.
cookie_name = "Counter_Cookie";
function doCookie() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookie_name+"=1; expires=Tuesday, 01-Apr-1999 08:00:00 GMT";
} else {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = eval(document.cookie.substring(countbegin, countend)) + 1;
document.cookie=cookie_name+"="+count+"; expires=Tuesday, 01-Apr-1999 08:00:00 GMT";
}
}
function gettimes() {
if(document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == -1) {
countend = document.cookie.length;
}
count = document.cookie.substring(countbegin, countend);
if (count == 1) {
return ("count+" time");
} else {
return ("count+" times");
}
}
}
return ("0 times");
}
<BODY> tag with the
event handler of: onUnload="doCookie()". The <BODY> tag for
this page looks like:
<BODY onUnload="doCookie()">
Finally, it's called by a regular
"document.write(gettime())" line in the HTML... and that's
all there is to it.
I am virtually all self-taught in all my programming and I got here by looking at other people's code. Far be it from me to not offer the same to other people learning JavaScript. I did, however stumble on the JavaScript/cookie codes all by myself.
If, however, you really must give thanks then a simple blurb about where you got this stuff would suffice. Note the link to Andy's Cookie Pages above.
Cheers,
Marc.