Create a JavaScript Counter

Written by:  • Edited by: Michele McDonough
Updated May 24, 2010
• Related Guides: Javascript

Do you want to keep track of the number of visitors to your website? Create your own personalized JavaScript web counter for your web page. Read the complete article to get the step by step guide for creating the counter.

Source Code for JavaScript Web Counter

Are you thinking of adding a JavaScript web counter to your website? Do you want to keep track of the number of hits that your site gets? To create your own personalized counter, all you need to do is embed a cookie function script to your web page. There are a number of scripting languages you can use, including some server side scripting languages. But the one coded with the client side JavaScript is equally able to serve your purpose.

All you need to activate the counter is to copy the following cookie function script and paste it between the <HEAD>…</HEAD> tags of your HTML document.

Step by Step Guide:

The first step should be to create an instance of the Date object and then fix the bug in Navigator 2.0, Macintosh, which is as follows;

var now = new Date ();

fixDate (now);

The next step is to take a note of the time setting, which goes like this,

Cookie expires in one year (or 365 days)

365 days in a year, 24 hours in a day, 60 minutes in an hour, 60 seconds in a minute and 1000 milliseconds in a second.

The code for the time setting is as follows;

now.setTime (now.getTime () + 365 * 24 * 60 * 60 * 1000);

var visits = getCookie (“counter”);

Note that in case the cookie is not found, this is the first visit. Set the value for the new cookie as follows;

if (!visits) {

visits = 1;

document.write (“This is your first visit here.”);

} else {

visits = parseInt (visits) + 1;

document.write (“This is your” + visits + “visit here.”);

}

Now finally set the new cookie as follows;

setCookie (“counter”, visits, now);

Finally Wrapping It Together

<SCRIPT LANGUAGE="JavaScript">

<!--

// create an instance of the Date object

var now = new Date();

// fix the bug in Navigator 2.0, Macintosh

fixDate(now);

/*

cookie expires in one year (actually, 365 days)

365 days in a year

24 hours in a day

60 minutes in an hour

60 seconds in a minute

1000 milliseconds in a second

*/

now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);

var visits = getCookie("counter");

// if the cookie was not found, this is your first visit

if (!visits) {

visits = 1; // the value for the new cookie

document.write("This is your first visit here.");

} else {

// increment the counter

visits = parseInt(visits) + 1;

document.write("This is your " + visits + " visit here.");

}

// set the new cookie

setCookie("counter", visits, now);

// -->

</SCRIPT>


 
blog comments powered by Disqus
Email to a friend