JavaScript Visitors
Counter
Welcome!
By
Dr Alex
As part of personalising your
visitors' experience, you might want to
show them how many times they visited
you.
This is easily achieved by using
JavaScript and storing a cookie on your
visitor's machine.
To see it at work, refresh/reload this
page and observe the changes to the
Welcome! line above.
To implement the counter:
Launch
JavaScript Editor and copy and
paste the code below to the
<head> section of the web
page:
<script language="javascript">
function DisplayVisits()
{
// How many visits so far?
var numVisits = GetCookie("numVisits");
if (numVisits) numVisits = parseInt(numVisits) + 1;
else numVisits = 1; // the value for the new cookie
// Show the number of visits
if (numVisits==1) document.write("This is your first visit.");
else document.write("You have visited this page " + numVisits + " times.");
// Set the cookie to expire 365 days from now
var today = new Date();
today.setTime(today.getTime() + 365 /*days*/ * 24 /*hours*/ * 60 /*minutes*/ * 60 /*seconds*/ * 1000 /*milliseconds*/);
SetCookie("numVisits", numVisits, today);
}
</script>
Copy and paste
the code below in the <body>
section of the web
page:
<script language="javascript">DisplayVisits();</script>
Please note that the code uses
SetCookie() and GetCookie functions to set
and retrieve the cookies: see getting and setting cookies using JavaScript.
When you use JavaScript
Editor, you will find the
cookies functions in 's Project pane, Solutions tab, Cookies.js. Link to Cookies.js in the <head>
section of your page:
<script
language="javascript"
src="Cookies.js"></script>
Alternatively,
copy and paste the cookie functions you
need. ...
|