Thursday, March 28, 2024

So You Want A Cookie Counter, Huh?


Use these to jump around or read it all…



[The Effect]
[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.



The Effect

The following script has three parents: me, a gentleman named Mac, who submitted something similar to me, and a JavaScript cookies help site which also offered something similar. I took parts of from each, found an easier method of setting the expires date, and this is what I came up with.



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



Cookie Count Script



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.



Cookie Count Script Explanation


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.

 


Enjoy!

 

[The Effect]
[Get the Script]
[Explaining the Script]

Previous article
Next article

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured