Program a function that will show the visitor how long time they have spent on your site. When they leave, we use a javascript onUnload-function to alert the user with the number of seconds.

Javascript can be used for lots of things. I got this idea some minutes ago and thought that I write it down for more people to use. The reason I thought about this, is that I wondered how long time I spent reading an other tutorial :-)

I don’t know if the function in it self is useful on a serious website, but I think that you can use the function to build special things for your needs.

Ok,now lets get to the magic… This is separated in two parts. On part that is activated when you visit the page, and one part that is activated when you leave the page.

<script language=”Javascript”>
pageOpen = new Date();

// This function is called when the person closes the window or navigate away.
function leavingPage()
{
pageClose = new Date();

hours    = (pageClose.getHours() – pageOpen.getHours());
minutes = (pageClose.getMinutes() – pageOpen.getMinutes());
seconds = (pageClose.getSeconds() – pageOpen.getSeconds());
time = (seconds + (minutes * 60) + (hours * 60 * 60);

time = (time + ” second(s)”);

if(time <= 60)
{
alert(‘You have visited this site ‘ + time + ‘. Next time I think you should stay longer than one minute…’);
}
else
{
alert(‘You have visitied this site ‘ + time + ‘. Thanks a lot, you are a valued visitor…’);
}
}
</script>

<body onUnload=”leavingPage()”>

This part is made up of three parts.

  1. Create a date object with the time when the page is generated (when the page is visited)
  2. When you leave the last part is triggered with the onUnload event, which calls our function “leavingPage()”. This function calculate and show the visitor the number of seconds spent on the site.

leavingPage-function

A simple explanation of what the function does.
First we create a  date object, just like we did when we started the page. But this object will hold information about the time when the visitor leave the site.

On a date object we have lots of different functions, and we will use three of them to get seconds, minutes and hours. Probably the person will never stay one hour, but youget the point hehe :-)

This row: “time = (seconds + (minutes * 60) + (hours * 60 * 60);” get the number of seconds from the start to the time the visitor leave.

After that I just do a small thing for fun… (I guess that I am a little bit bored when I consider that fun…, but anyway). We do a check if the visitor has been at the site more than one minute and show a message that thank the visitor. If the visitor has been at the site less than 60 seconds theyget a message that they should stay longer next time.

Hope you find this useful for something, or atleast good for learning :-)

Similar Posts:

  • Share/Bookmark