html - Set an initial value for a Javascript Count Down Timer -
i trying make countdown timer starts click of button.
i have gotten work minutes , seconds cannot seem figure out how static time display prior button click.
what wondering how time display on webpage above start button (in case 59 min 59 sec) , start countdown function once button hit?
<head> <input type="button" onclick="countdown('countdown');" value="start" /> <script type="text/javascript"> var cdtime; var minutes = 59; var seconds = 59; function countdown(element) { cdtime = setinterval(function() { var timer = document.getelementbyid(element); if(seconds == 0) { if(minutes == 0) { alert(timer.innerhtml = "countdown's over!"); clearinterval(cdtime); return; } else { minutes--; seconds = 60; } } if(minutes > 0) { var minutetxt = minutes + (minutes > 1 ? ' minutes' : 'minute'); } else { var minutetxt = ''; } var secondstxt; if(seconds > 1) { secondstxt = 'seconds'; } else { secondstxt = 'second'; } timer.innerhtml = minutetxt + ' ' + seconds + ' ' + secondstxt; seconds--; }, 1000); } </script> </head> <body> <div id='countdown'></div> </body> </html>
create div , use set inner html of div using javascript (i did after defining minutes , seconds).
also bring elements out of header , bring them inside body
- if don't use jquery wait window complete loading, bring script after html elements.
var cdtime; var minutes = 59; var seconds = 59; document.getelementbyid("initialtime").innerhtml=minutes+":"+seconds; function countdown(element) { cdtime = setinterval(function() { var timer = document.getelementbyid(element); if(seconds == 0) { if(minutes == 0) { alert(timer.innerhtml = "countdown's over!"); clearinterval(cdtime); return; } else { minutes--; seconds = 60; } } if(minutes > 0) { var minutetxt = minutes + (minutes > 1 ? ' minutes' : 'minute'); } else { var minutetxt = ''; } var secondstxt; if(seconds > 1) { secondstxt = 'seconds'; } else { secondstxt = 'second'; } timer.innerhtml = minutetxt + ' ' + seconds + ' ' + secondstxt; seconds--; }, 1000); }
<body> <div id="initialtime"></div> <input type="button" onclick="countdown('countdown');" value="start" /> <div id='countdown'></div> </body>
Comments
Post a Comment