I have built a simple countdown timer, and am wondering how I can make it so once the countdown is finished I can change the timer to a div that tells the user the countdown is completed? Currently it will just add negatives to countdown like this:
As it counts down:
[ 01 ][ 01 ][ 10 ][ 30 ]
days hours mins secs
Once it reaches past time limit:
[ 00 ][ -01 ][ -10 ][ -30 ]
days hours mins secs
I'm not really sure where to even start on this, but here is how my timer is set in HTML
Timer HTML:
<div class="timer">
<div><div id="d"></div>days</div>
<div><div id="h"></div>hours</div>
<div><div id="m"></div>min</div>
<div><div id="s"></div>sec</div>
</div>
and my JS functions:
// vars for current year
var current = new Date();
//Your current year
var current_year = current.getFullYear();
//Next year
var next_year = current_year + 1;
// Date you will count down to
// You can change the 'current_year' to 'next year' as well if you were counting down to someing in 2016
var target_date = new Date("july 4, " + current_year).getTime();
// Vars for units of time
var days, hours, minutes, seconds;
// Get the elements that will hold the numbers.
var $days = document.getElementById("d");
var $hours = document.getElementById("h");
var $minutes = document.getElementById("m");
var $seconds = document.getElementById("s");
// Calculate the countdown clock and set the HTML.
function update() {
// Find the amount of "seconds" between now and target.
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// Do some time calcs
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// Format the number strings and put them in the elements.
$days.innerHTML = pad(days, 2);
$hours.innerHTML = pad(hours, 2);
$minutes.innerHTML = pad(minutes, 2);
$seconds.innerHTML = pad(seconds, 2);
}
// update the HTML
// or else your boxes will be blank
update();
// update every 1 second.
setInterval(update, 1000);
// If num has less than size digits, add enough 0s to the front.
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
And a codepen to further help explain.
I imagine I would need something along the lines of..
var
to represent 'completed'var
completed is satisfied, change the class of timer
? I'm really not sure, any help is appreciated!
All you want to know is
Is the countdown is before or after
now
.
First put your interval
in a var like this:
var countdownInterval = setInterval(update, 1000);
Second, in your update()
function, add:
if(target_date <= Date.now()) {
clearInterval(countdownInterval);
document.querySelector(".timer").innerHTML = "Countdown ended!"
}