Reputation: 8457
I got this code from here. However, I am not too great with JS and need a little help getting the timer to not reset on reload. Also, I want it to countdown days instead of hours, minutes, and seconds. Can somebody please help me out?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<script>
/*<![CDATA[*/
function zxcCountDown(id,mess,secs,mins,hrs,days){
var obj=document.getElementById(id);
var oop=obj.oop
if (!oop){
obj.oop=new zxcCountDownOOP(obj);
}
obj.oop.start(mess,secs,mins,hrs,days);
}
function zxcCountDownOOP(obj,mess){
this.obj=obj;
this.to=null;
}
zxcCountDownOOP.prototype={
start:function(mess,secs,mins,hrs,days){
clearTimeout(this.to);
this.mess=mess;
this.mhd=[mins,hrs,days];
var date=new Date();
this.fin=new Date(date.getFullYear(),date.getMonth(),date.getDate()+(days||0),date.getHours()+(hrs||0),date.getMinutes()+(mins||0),date.getSeconds()+(secs||0));
this.cng();
},
cng:function(){
var now=new Date(),s=(this.fin-now)/1000+1,d=Math.floor(s/60/60/24),h=Math.floor(s/60/60-d*24),m=Math.floor(s/60-h*60-d*24*60),s=Math.floor(s-m*60-h*3600-d*24*60*60);
if (this.fin-now>-500){
this.obj.innerHTML=(this.mhd[2]?(d>9?d:'0'+d)+' days ':'')+(this.mhd[1]||this.mhd[2]?(h>9?h:'0'+h)+' hours ':'')+(this.mhd[0]||this.mhd[1]||this.mhd[2]?(m>9?m:'0'+m)+' minutes ':'')+(s>9?s:'0'+s)+' seconds';
this.to=setTimeout(function(oop){ return function(){ oop.cng(); }}(this),1000);
}
else if (this.mess){
this.obj.innerHTML=this.mess;
}
}
}
/*]]>*/
</script></head>
<body onload="zxcCountDown('tst','message',20); zxcCountDown('tst1','message 1',0,0,2,0);">
<span id="tst" ></span> <input type="button" name="" value="Re-Start" onmouseup="zxcCountDown('tst','message',20);"/>
<br />
<span id="tst1" ></span>
</body>
</html>
Upvotes: 1
Views: 175
Reputation: 2432
Technically, you can't. Javascript does not maintain state on load. There are several options, though.
That's about it, though.
Upvotes: 2
Reputation: 6926
javascript is a client side script. And it does reloads each time the page is reloaded. To persist the variables, you will need to look into something outside the script.
Did you try to use cookies ?They can save your variable values for as long as you want.
Just fetch the value from cookies at each reload
Upvotes: 0