Its_ToXiiC Its_ToXiiC - 3 months ago 8
Javascript Question

Add "0" to countdown timer after it reaches 0

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 + '.&nbsp;&nbsp;&nbsp;';
document.getElementById(id).innerHTML += hours + '.&nbsp;&nbsp;&nbsp;';
document.getElementById(id).innerHTML += minutes + '.&nbsp;&nbsp;&nbsp;';
document.getElementById(id).innerHTML += seconds + '.';
}

timer = setInterval(showRemaining, 1000);
}

Answer

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.

Comments