I want to use the following to make the code start only by the press of a button rather than the code starting on its own when the page loads. also adding a reset button too.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var interval;
var minutes = 5;
var seconds = 10;
window.onload = function() {
countdown('countdown');
}
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
alert(el.innerHTML = "countdown's over!"); 开发者_JAVA百科
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? 'seconds' : 'second';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
seconds--;
}, 1000);
}
</script>
</head>
<body>
<div id='countdown'></div>
</body>
</html>
instead of onload use this
<input type="button" onclick="countdown('countdown');" value="Start" />
for reset, use this
<input type="button" onclick="minutes=5;seconds=10;" value="Reset" />
The code that triggers the countdown is here:
window.onload = function() {
countdown('countdown');
}
instead, you can erase that and inline a button in the content that triggers the countdown with an onclick behavior:
<a href="javascript:void(0);" onclick="countdown('countdown')">Click Me to Start</a>
The timer is stored in your
var interval;
To stop it, you can put in another button that calls clearInterval(interval):
<a href="javascript:void(0);" onclick="clearInterval(interval)">Click Me to Stop</a>
To reset, do what the others suggested and store a new value in the minutes, seconds :)
you will need the two buttons:
<input type="button" value="reset" id="reset" />
<input type="button" value="start" id="start" />
and the javascript for them:
var reset = document.getElementById('reset');
reset.onclick = function() {
minutes = 5;
seconds = 10;
clearInterval(interval);
interval = null;
}
var start = document.getElementById('start');
start.onclick = function() {
if (!interval) {
countdown('countdown');
}
}
example here
seconds = 60;
You have to reset the seconds to 59, because otherwise you count 60 twice. One time with the 0 and one time with the 60.
精彩评论