Count how much time user has spent on current page
If you would like to present an information to your user on how much time did he or she spend on your webpage, then here is a particular example on how to do this the easiest way I found.
Lets start with simple Javascript code:
[code language=”javascript”]
var startTime = new Date();
function countTimeSpentHere()
{
var currentTime = new Date();
var timerDiv = $("#timer");
var differenceTime = currentTime – startTime – 3600000; //Small, but required fix…
var differenceDate = new Date(differenceTime);
timerDiv.html(formatTime(differenceDate, "HH:MM:SS"));
}
window.setInterval(countTimeSpentHere, 1000);
[/code]
I’m using a jQuery selector $("#timer")
here to catch a div
, where time passed by will be presented. If you don’t use jQuery on your page, you have to replace this line with:
[code language=”javascript”]
var timerDiv = document.getElementById("timer");
[/code]
and then replace:
[code language=”javascript”]
timerDiv.html(formatTime(differenceDate, "HH:MM:SS"));
[/code]
with:
[code language=”javascript”]
timerDiv.innerHTML = formatTime(differenceDate, "HH:MM:SS");
[/code]
I’m also using here a formatTime()
function, which you may find here to format time spent on current page.
If you don’t need nifty time formatting and prefer only a number of seconds passed since user has entered page, you can forget about formatTime()
function and use something like this instead:
[code language=”javascript”]
function countTimeSpentHere()
{
var currentTime = new Date();
var timerDiv = $("#timer"); //or document.getElementById("timer");
var differenceTime = Math.round((currentTime – startTime) / 1000);
timerDiv.html(differenceTime);
}
[/code]
That’s all folks!