Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate and Display Total Time Online on Website

Status
Not open for further replies.

meerkat2

Programmer
Mar 25, 2009
4
GB
Hello,

I have a Javascript that calculates and displays how long, in minutes
and seconds a user has been in online(Google Gears development) mode on a given web
page. I need however, to modify the script so that it calculates and
displays how long the user has been online on the web site.
For e.g. on page 1 for 2 minutes 12 seconds.
Moves to page 2 - total time on page 1 and 2= 4 minutes 13 seconds.
My script (see below) starts a second counter then converts that to minutes and seconds.
I have tried passing the secVar0 variable in the url but that comes back "undefined".

Does anyone have any pointers please?
Thanks,
meerkat
p.s. I can't use server-side solution!



Code:
if(request.responseText != "" && request.responseText.indexOf("404 Page not found") == -1)
    {
        c=0;
        var startTicker = startCount1();
         secVar0 = startTicker;
        minVar = Math.floor(secVar0/60);
        secVar = secVar0 % 60;       
        document.getElementById('Text1').innerHTML = "Time Online: " +" Minutes: " +minVar+" Seconds: "+ secVar;
        document.getElementById('serverstatus').innerHTML = '<img src="online.gif">'; 
      
    }
 
Hi

meerkat2 said:
I can't use server-side solution!
Then just store the visit time between page loads in a cookie.

However would be a good question what will happen if the visitor opens multiple pages of you site simultaneously in separate tabs/windows.

Feherke.
 
Alternate Solution:

You could pass the value of the timer using the onLoad event in your body tag and adjust all the "a" tags in your code to include "#totaltime". On each page load add the total time to the current time. Mind you, it's not a bullet proof way of doing it as someone could potentially change the value in the url and it would mess up the timer.

This problem got me thinking and I did write something that achieves the effect (needs lots of work, but it could get you going in the right direction if you choose this method). I just want to know why you can't use the server to do this (it would be WAY easier and more bullet proof).

Is it for an actual real life project or some sort of a school project?


TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
Thanks feherke and vicvirk for your replies.
I will try the cookie solution perhaps.
vicvirk, I can't use server-side because the app is for a mobile device without internet connection.

vicvirk, would you let me have a look at your code?

Thanks,
meerkat
 
Demo Here:


Note: written very quickly and loosley, it's not bullet proof, rather just meant to demo the concept. You'll notice two sets of values at the bottom - one that shows the current time on the current page, the other show the current time on the site. The timer is based on the hash value (test1.html#4) which is passed page to page.

It's written to track in seconds, you should easily be able to convert that to minutes:seconds....


Code:
<html>
<head>
<script>
 var timer;
 var ttlTimer; 
 function incrementTimer() {
  timer++;
  document.getElementById("timerTHIS").innerHTML = parseInt(timer) - parseInt(ttlTimer);
  setTimeout("incrementTimer()",1000);
 }
 
 function pageInit() {
  var lnks = document.getElementsByTagName("a");
  for (i = 0 ; i < lnks.length; i++) {
   cLoc = lnks[i].href;
   nLoc = "javascript:navigate('" + lnks[i] + "')";
   lnks[i].href = nLoc;
   
  }
  cLoc = window.location.href;
  ra = cLoc.split('#');
  if (ra.length > 1) {
   timer = ra[1];
  }
  else {
   timer = 0;
  }
 document.getElementById("timerTTL").innerHTML = timer;
 ttlTimer = timer;
 incrementTimer();
 }
 
 function navigate(strInput) {
  window.location.href = strInput + "#" + timer;
  return false;
 }
 </script>
 </head>
<body onLoad="pageInit();">
 <a href="test1.html">Nav 1</a><br />
 <a href="test2.html">Nav 2</a><br />
 <a href="test3.html">Nav 3</a><br />
 <a href="test4.html">Nav 4</a><br />
 <br /><br />
 Total Seconds On This Page <span id="timerTHIS"></span><br />
 Total Seconds On Site <span id="timerTTL"></span>
</body>
</html>

TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
Thanks vicvirk for this code. It does point me in the right direction I think. I will work on it now.
Just a couple of follow up questions:
1. I already have links on the page in the form of-
Code:
var aElem = document.createElement('a');
        aElem.href="expand_activity.html?my_schedule_id="+sid2+"&user_id="+uid2+"&main_detail_id="+mdid2;

How would your code interact with my code?

What strategy would I need to follow so the code doesn't break if the user clicks on the same page? For e.g. if user is on home page and then clicks the icon to go to the home page.

Thanks for your input.

meerkat
 
If you are dynamically creating links with javascript, you will need to add the same hash value to the end just like I did in the pageInit function. I don't think (and am almost certain of it) the script will add it to any dynamically created links.

Code:
var aElem = document.createElement('a');
        aElem.href="expand_activity.html?my_schedule_id="+sid2+"&user_id="+uid2+"&main_detail_id="+mdid2[b]+"#"+timer[/b];

As far as the link not breaking, that's up to you. Sorry for being blunt, but I wrote a good chuck of code to get you started, and I don't have time/nor am I getting paid to debug it any further...the only thing I can think of off the top of my head is wrapping it in some sort of a condition (don't know what that condition is).

feherke's way of doing it will work too, you can use the same theory as my version but instead of writing into the hash value you write into a cookie...both methods have their ups/downs. As feherke mentioned, the cookie method's behaviour is unknown if the client opens another browser to the same page. My method will break if the user changes the number OR refreshes the page....

Good luck, if you are still having problems once you've implemented either version, let us know and we'd be glad to help (feherke, sorry I'm speaking for you, but I'm assuming you would help if some more work was done)...


TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
Hello,
Thanks for all your assistance so far.
I am trying the cookie version.
This is what I have:

On Page 1 in the Head:
Code:
<script language="javascript" type="text/javascript">
var startTicker =0;
  var minVar = 0;
  var secVar = 0;
  var secVar0;
function initCookie()

{
		var minsinsecs =minVar*60;
		var total = minsinsecs + secVar;
		createCookie("total",total,1);
		
		var valuefromcookie = readCookie('total')
		if (valuefromcookie) 
		{
			//secVar0 = 1;
			secVar0 = parseInt(valuefromcookie);
			//secVar0 = parseInt(valuefromcookie) + parseInt(startTicker);
		}
		else
		{
			secVar0 = 0;
		}
		//document.write(secVar0);
}


</script>

On the rest of page 1 and subsequent pages I have:
Code:
<script type="text/javascript" language="javascript">
  var minVar;
  var secVar;
  var secVar0;
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
 
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
 
function eraseCookie(name) {
    createCookie(name,"",-1);
}
</script>

Then:
Code:
var b=0;
var y;
function startCount1()
{
    document.getElementById('Text1').value=b
    b=b+1;
	return b;
	y=setTimeout("startCount1()",1000);
	
}
Then:
Code:
var numPings = 0;
  
//  var minVar;
//  var secVar;
  var totalSecs;
  var request = google.gears.factory.create('beta.httprequest');
  var TIME_BETWEEN_PINGS = 1*1000;
  var PING_TIMEOUT_SECONDS = 1*1000;
  function pingSuccess() 
  {
	
    if(request.responseText != "" && request.responseText.indexOf("404 Page not found") == -1)
	{
		c=0;
		startTicker = startCount1();
		//secVar0 = startTicker;
		totalSecs = readCookie('total');
		var ttsecs = parseInt(totalSecs);
		
		if (ttsecs) 
		{
			secVar0 = ttsecs +parseInt(startTicker);
			
		}
		else
		{
			//secVar0 =0;
			secVar0 = ttsecs +parseInt(startTicker);
		}
		 
		minVar = Math.floor(secVar0/60); 
		secVar = secVar0 % 60;		
		document.getElementById('Text1').innerHTML = "Time Online: " +" Minutes: " +minVar+" Seconds: "+ secVar; 
        document.getElementById('serverstatus').innerHTML = '<img src="online.gif">';	
		
	   
	}

	else 
	{     	
		b=0;
		var startTicker2 = startCount2();
		secVar2 = startTicker2;
minVar2 = Math.floor(secVar2/60);  
secVar3 = secVar2 % 60;
      
		document.getElementById('Text1').innerHTML = "Time Offline: " +" Minutes: " +minVar2+" Seconds: "+ secVar3; 
		document.getElementById('serverstatus').innerHTML = '<img src="offline.gif">';

	  	
    }
	
	
  }
	
  function isServerAvailable() 
  {  
    var resource_to_test = "FAQs_to_write.txt";  
    resource_to_test += "?q=" + Math.floor(Math.random() * 100000);  
    request.open('GET', resource_to_test);  
    window.setTimeout("pingSuccess()",PING_TIMEOUT_SECONDS);  
    request.onreadystatechange = function()
	 {    
      if (request.readyState == 4)
	  {
        numPings++;
		secVar5 = numPings;
	minVar3 = Math.floor(secVar5/60);  
	secVar4 = secVar5 % 60;
        document.getElementById('pings').innerHTML = "Time on PDA: " +" 	Minutes: " +minVar3+" Seconds: "+ secVar4; 
	}
    };
	
    request.send();
    window.setTimeout("isServerAvailable()",TIME_BETWEEN_PINGS);
  }
isServerAvailable();
var mintosecs = minVar*60;
var total = mintosecs + secVar;
createCookie("total",total,1)

Finally just before pages unloads:
Code:
window.onbeforeunload = setTotalSecs;
  function setTotalSecs()
  {
	  
	var min2secs = minVar*60;
	var total = min2secs + secVar;
	//var total = startTicker;
	createCookie("total",total,1)
  }
What is happening? On page 1 it is counting to about 15 seconds then jumping to 32. When it gets there is appears to be counting OK and converting to mins/secs.
Then when it moves to page 2 I am getting NaN for both minutes and seconds.

Can you see where I am going wrong?
Thanks,
meerkat
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top