Use these to jump around or read it all…
[Get the Script]
[Explaining the Script]
I wrote two cookie tutorials one right after the other. Both were written in response to Goodies reader requests. In the first tutorial, I put together a script that would place and retrieve a cookie. Go see it if you haven’t already.
In this tutorial, I’m going to use a cookie to count the number of times a computer has been to your site. The purpose of the script is to place the cookie and retrieve it, adding one each time it visits.
Now, to be fair, this counter will only work as long as the person allows the cookie to stay put. The moment he or she goes into the guts of their browser directory and erases the cookie, the count is dead.
Also, before you start placing cookies all over the Net, please take the time to read my cookies reference piece. Many people don’t want you placing cookies. You need to decide if this counter is worth the hassle it might bring you.
That said, we’ll move on.
document.write(“You have been to this page “+gettimes()+” before.“);
(Hit reload a couple of times to up the count!)
Get the Script
Like I said in the last cookie tutorial, setting these things can be rough. Luckily, this one is a simple copy-and-paste and you’re done. If you’re already setting a cookie called Counter_Cookie, that could get in the way, so be careful with naming.
Here’s the code. Copy and paste it just as you see it.
Explaining the Script
Since this is, for the most part, a straight copy and paste, let me simply offer the script again in text form and explain what each section does. If you’ve read the other cookie tutorial, this should make quick sense.
More Than One
If you intend to use the counter script on multiple pages, keep in mind that you’ll need to assign a new cookie name for each page. If you don’t, all the pages containing the script will affect the same cookie and the count will be a total of all the pages on your site the person has visited rather than a count of that one page. Now, maybe you want that as it would certainly kick the number up faster…
…but if you’re a good, decent, honorable human being (and I know you are) and want your counts to reflect true visitation numbers, then make sure you change the name of the cookie every time you place this script on a page. You only have to change it once, in the third line of the script.