Reputation: 391
So basicly what I would like to do is have my countdown timer add a "0" once it reaches below "10". So far I have tried an if statement (In code below) which did not work. Here is my full code:
CountDownTimer('01/1/2017 12:0 AM', 'countdown');
CountDownTimer('01/1/2017 12:0 AM', 'newcountdown');
function CountDownTimer(dt, id)
{
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
// THIS IS THE "IF" STATEMENT THAT DID NOT WORK, EVERYTHING ELSE IS WORKING
if (seconds < 10) {
document.getElementById(id).innerHTML += '0' + seconds + '.';
}
document.getElementById(id).innerHTML = days + '. ';
document.getElementById(id).innerHTML += hours + '. ';
document.getElementById(id).innerHTML += minutes + '. ';
document.getElementById(id).innerHTML += seconds + '.';
}
timer = setInterval(showRemaining, 1000);
}
Upvotes: 0
Views: 227
Reputation: 102174
The problem with your code is not the if
, which is working:
if (seconds < 10) {
document.getElementById(id).innerHTML += '0' + seconds + '.';
}
But the fact that, just after that, you are overwriting the previous value:
document.getElementById(id).innerHTML += seconds + '.';
An easy solution is converting seconds
to an string, in your if
:
if (seconds < 10) {
seconds = "0" + seconds;
}
This way, you can use the string in your subsequent innerHTML
.
Upvotes: 0
Reputation: 41
From what I see, your If-statement is working correctly. However, right after your If-statement you have
document.getElementById(id).innerHTML = days + '. ';
This is going to overwrite your previous declaration setting the innerHTML to days + '. '
.
Try setting your seconds in the If-statement so that the last line uses the updated seconds.
Upvotes: 0
Reputation: 206048
This should do it:
// THIS IS THE "IF" STATEMENT....
if (seconds < 10) {
seconds = "0"+ seconds;
}
than to construct your output use:
document.getElementById(id).innerHTML = days + '. '+
hours + '. '+
minutes + '. '+
seconds + '.';
Also, your expiration should be at <=0
not at <0
Upvotes: 1