Can someone please help me implement two javascript counters inside a single page? I currently have the counter up and running but when I try to create a new div for another counter, the original counter disappears and only one counter is displayed. This is my first post so please excuse any messed up formatting. I would greatly appreciate any help, I’m quite new to javascript. Thank you!
Here is my code:
<div id="counter"></div>
<div id="counter1"></div>
<script type="text/javascript">
var START_DATE = new Date("July 27, 2010 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 9001; // initial value when it's the start date
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML =
addCommas(count);", msInterval);
}
</script>
<script type="text/javascript">
var START_DATE = new Date("July 27, 2011 13:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 2; // increase per tick
var START_VALUE = 8001; // initial value when it's the start date
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval) * INCREMENT + START_VALUE;
document.getElementById('counter1').innerHTML = addCommas(count);
setInterval("count += INCREMENT; document.getElementById('counter1').innerHTML =
addCommas(count);", msInterval);
}
</script>
<script type="text/javascript">
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
</script>
You cannot have two
window.onloadscripts, the last one will overwrite the first one.Just reuse the same code and simply add the next counter to the next div.
EDIT: Increment count only once, otherwise the second counter is ahead of the first always