Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript countdown adding start and reset buttons

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!");                    
                    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>
like image 654
jennifer Avatar asked Aug 27 '26 22:08

jennifer


2 Answers

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" />
like image 67
strauberry Avatar answered Aug 30 '26 11:08

strauberry


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 :)

like image 35
jbrookover Avatar answered Aug 30 '26 12:08

jbrookover



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!