Javascript code do not count date properly - javascript

I am using this code in order to countdown a date:
function countdown()
{
var now = new Date();
var end = new Date('Mars 13, 2016 13:12:12'),
$.each(times, function( key, value ) {
var left = end - now;
var days = Math.floor( left / (1000 * 60 * 60 * 24) );
var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
var seconds = Math.floor( (left % (1000 * 60)) / 1000 );
displayTime = '';
if (days > 0) {
displayTime = days+' days';
}
displayTime = displayTime + ' ' +hours+' Hours ' + minutes+' Minutes ' + seconds+'s';
$('#cont'+value.id).text(displayTime)
});
}
But it doesn't counts it properly since it is not considering if month have 31 days, 28/29 days ...
And the second thing is that when it reaches the expiring date, It does not stops and continues to count down below zero.
What have i done wrong, and how to fix it please ?

The way that I do countdowns is to create a countdown initiation script called countdown.js, and then include this script in your main page with the script tag's src="countdown.js"
Here is the code for countdown.js
CountDownTimer('12/25/2016 12:0 AM', 'countdown');
//CountDownTimer('02/20/2012 10:1 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 = 'Merry Christmas!';
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);
if(hours < 10){
hours = "0"+hours;
}
if(minutes < 10){
minutes = "0"+minutes;
}
if(seconds < 10){
seconds = "0"+seconds;
}
document.getElementById(id).innerHTML = "<span id='daycount'>" + days + ' days</span><br/>';
document.getElementById(id).innerHTML += hours + ':';
document.getElementById(id).innerHTML += minutes + ':';
document.getElementById(id).innerHTML += seconds + '';
}
timer = setInterval(showRemaining, 1000);
}
Now on your main page
Include the countdown script with <script src="countdown.js"></script> in your <head>.
Then create a div with id="countdown".
The countdown div's id is defined by the first line of the countdown.js script, as the second function input for CountDownTimer();.
My code is set to count down to christmas, you change change this date and time easily by modifying the first line of countdown.js to suit your date needs. Make sure you use the same format as the supplied date though! mm/dd/yyyy H:m AM/PM

You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing). Either write a small function yourself or use a library.
Also, if your code depends on a particular library, you should include a tag for that. There are many posts here on how to create a timer.
The code you've posted does not have any months so it's unclear why you're having an issue with them. Perhaps you want to count down years, moths, days, etc.? That's a much more difficult issue than just days, hours, etc. and there are questions and answers for that too.
var countDown = (function() {
var endDate;
return function(eDate) {
endDate = endDate || eDate;
var msg = '';
var now = Date.now();
var r = endDate - now;
var d, h, m, s;
if (r <= 1000) {
msg = 'Finished!';
} else {
d = r / 8.64e7 | 0;
h = r % 8.64e7 / 3.6e6 | 0;
m = r % 3.6e6 / 6e4 | 0;
s = r % 6e4 / 1000 | 0;
msg = (d? d + ' day' + (d == 1? '':'s') + ', ' : '') +
h + ' hour' + (h==1?'':'s') + ', ' +
m + ' minute' + (m==1?'':'s') + ' and ' +
s + ' second' + (s==1?'':'s');
}
document.getElementById('counter').textContent = msg;
var lag = 1010 - (Date.now() % 1000);
if (r > 0) {
setTimeout(countDown, lag);
}
}
}());
countDown(new Date(2016,11,25));
<span id="counter"></span>

Related

How can I prevent this daily countdown timer from resetting at midnight?

Key variables to keep in mind:
This is set to simulate 11:00 PM.
var bt = "23:00";
This is set to simulate 8:00 AM.
var wt = "08:00";
The desired functionality:
The countdown timer starts every morning at 8:00 AM.
It counts down until 11:00 PM, every night.
Then it stays at 00:00:00.
In the morning, at 8:00 AM, it repeats the count-down, again.
This should happen forever.
What is actually happening:
Everything is working fine, except it is starting a 24 hour countdown at midnight, until 8:00 AM.
I have tried debugging this, and I suspect the error lies in what is calculated as the distance variable, making the code think that it is comparing against the next day, but I am not sure how to remedy this.
Here is the Codepen.
and here is my JS code:
$(document).ready(function () {
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dateNow = moment().format('MMM D, YYYY');
placeHolderDate = dateNow + " " + bt;
var timeNow = moment().format('HH:mm');
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// Update the count down every 1 second
var x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
var timeNow = moment().format('HH:mm');
//console.log('Time Now:' + timeNow);
//console.log('Wake Time:' + wt);
if (timeNow === wt) {
clearInterval(x);
restartCountdown();
}
//console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
function restartCountdown() {
//log("restartCountdown Started!");
var bt = "23:00"; // 11:00 PM
var wt = "08:00"; // 08:00 AM
var dN = (moment().add(moment.duration({d: 1})).format('MMM D, YYYY'));
console.log('dn ' + dN);
var placeHolderDate = dN + " " + bt;
var countDownDate = new Date(placeHolderDate).getTime();
var countDownHourMin = (wt.split(":"));
// Update the count down every 1 second
var x = setInterval(function () {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
if (hours < 0 || minutes < 0 || seconds < 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}
// console.log(hours + ":" + minutes + ":" + seconds);
}, 1000);
}
});
I have edited your code and created this codepen https://codepen.io/anon/pen/aabjEb?editors=0010. Please feel free to optimize the code since I have not done it. The idea was is check if time is between 8 AM and 11 PM. If yes show value else show 00:00:00. Also once the date changes, update the dates and now compute accordingly
$(document).ready(function () {
function countdown() {
var bt = "23:00", // 11:00 PM
wt = "08:00"; // 08:00 AM
var today = new Date(),
dd = today.getDate(),
mm = today.getMonth()+1,
yyyy = today.getFullYear();
var startTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + wt),
endTime = new Date(mm + '/' + dd + '/' + yyyy + ' ' + bt);
setInterval(function() {
var now = new Date();
var nowdd = today.getDate();
var nowTime = now.getTime();
if(dd !== nowdd) {
dd = nowdd;
var nowmm = now.getMonth() + 1,
nowyyyy = now.getFullYear();
startTime = new Date(dd + '/' + mm + '/' + yyyy + ' wt');
endTime = new Date(dd + '/' + mm + '/' + yyyy + ' bt');
}
if(nowTime > startTime && nowTime < endTime) {
// Find the distance between now and the count down date
var distance = endTime - nowTime;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)),
seconds = Math.floor((distance % (1000 * 60)) / 1000);
$("#countDown").val(hours + ":" + minutes + ":" + seconds);
} else {
$("#countDown").val("00:00:00");
}
}, 1000);
}
countdown();
});

How to add time picker in HTML5 which have HH:MM format with selected Dates?

I searched everywhere but I'm not satisfied by the answer. At last I'm posting here to get the answer.
I have two datepicker and time picker textbox which displays 12:00 format with AM & PM.
Here I want to calculate the TOTAL time which includes number of days and given time.
I want to add those time and display it in another text box. I need it in HH:MM format. I don't want seconds as my time picker textbox shows only HH:MM which is enough for me.
I tried many methods to add but i'm not getting the exact time value.
Below is my HTML code
<input type="date" id="opening_date">
<input type="date" id="closing_date">
<input type="time" class="time" id="garage_out_time">
<input type="time" class="time" id="garage_in_time">
<input type="text" id="total_hours">
Below is my script code
$(document).ready(function () {
function ConvertDateFormat(d, t) {
var dt = d.val().split('/');
return dt[0] + '/' + dt[1] + '/' + dt[2] + ' ' + t.val();
}
$(".time").change(function () {
var start = new Date(ConvertDateFormat($('#opening_date'), $('#garage_out_time')));
var end = new Date(ConvertDateFormat($('#closing_date'), $('#garage_in_time')));
console.log(start, end);
var diff = new Date(end - start);
var days = Math.floor(diff / 1000 / 60 / 60 / 24);
var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
var total = (days * 24) + hours;
var startTime = document.getElementById("garage_out_time").value;
var endTime = document.getElementById("garage_in_time").value;
var s = startTime.split(':');
var e = endTime.split(':');
var endtime = parseInt(e[1], 10);
var starttime = parseInt(s[1], 10);
var min = endtime + starttime;
var minutes = min ;
var minhours = Math.floor(minutes / 60);
minutes = minutes % 60;
total = total + minhours;
if(minutes > 9){
$("#total_hours").val(total+":"+ minutes);
} else {
$("#total_hours").val(total+":0"+ minutes);
}
});
});
Above code is working for some extent BUT for example when I select 8:12 AM to 8:12 PM , the result I'm getting is 12:32 where answer should be 12:00.
I think you are over-complicating things somewhat. Your ConvertDateFormat() function already gives you what you need, so why are you parsing the time again? Try the code below (with thanks to this this answer)
var start = new Date(ConvertDateFormat($('#opening_date'), $('#garage_out_time')));
var end = new Date(ConvertDateFormat($('#closing_date'), $('#garage_in_time')));
console.log(start, end);
var diff = new Date(end - start);
var mins = Math.floor( diff / 60000 % 60 );
var hours = Math.floor( diff / 3600000 % 24 );
var days = Math.floor( diff / 86400000 );
console.log('days='+days+' hrs='+hours+' mins='+mins);
var totalHours = (days * 24) + hours;
var minsStr = (mins < 10) ? '0' + mins : mins;
$('#total_hours').val(totalHours + ':' + minsStr);

Birthday Countdown

Im trying to write a program where the user enters their birthday and a countdown timer appears and counts down the months days hours and seconds until their birthday. Right now it is not not working and any help would be great! Thanks!
<body>
<script>
var end = new Date();
document.getElementById("myDate").value = end;
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var _month = _day * 30;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var months = Math.floor(distance / _month);
var days = Math.floor((distance % _month) / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = months + 'months ';
document.getElementById('countdown').innerHTML += days + 'days ';
document.getElementById('countdown').innerHTML += hours + 'hrs ';
document.getElementById('countdown').innerHTML += minutes + 'mins ';
document.getElementById('countdown').innerHTML += seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
</script>
Enter your birthday:
<br>
<input type="date" id="myDate">
<br>
<br>
<input type="button" onclick="showRemaining()" value="Enter">
<div id="countdown"></div>
</body>
There are a number of issues with your code as identified in other answers, I'll paraphrase:
The script runs before the elements exist in the DOM, so attempts to reference them return null and you'll get errors attempting to set its properties.
end is set as the page loads, so it's always in the past in respect to when the function runs, so end - now is either
zero (probably initially) or negative (more than 1 millisecond after assigning to end).
The button will allow multiple instance of setInterval to be running, so you'll get some pretty confusing results since they're all trying to set the value of countdown
The calculation is flawed as there aren't exactly 30 days in every month, nor 24 hours in every day if the host observes daylight saving. Fixing that isn't hard, but I'm not going to fix it here.
Don't use input type Date, support is patchy. You can test for support and handle cases where it isn't, but it's all a bit much for this exercise.
So, don't start the timer until the button is pressed (or some other event after the page is loaded), stop any timer that is currently running and reset end at the same time.
Note that setInterval will drift as it doesn't run at exactly every second, so every now and then it will skip two seconds. Also, invalid date input should be dealt with. Both can be fixed, but out of scope here. ;-)
// Don't set the value for end until the button is pressed.
var end; // = new Date();
// document.getElementById("myDate").value = end;
// Also need a global timer reference so it can be cancelled when required
var timer;
// Since listener is attached by addEventListener, event will only be passed
// if the call comes from the button
function showRemaining(event) {
// Function to cancel the timer
function stopTimer(){
if (timer) {
clearInterval(timer);
end = timer = null;
}
}
// Keep these local
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var _month = _day * 30;
// If click came from the button or timer isn't set, restart the timer
if (event || !timer) {
stopTimer();
timer = setInterval(showRemaining, 1000);
}
// Get the current date
var now = new Date();
// Get the value of countdown and parse it, see parsing function
// If end isn't set, set it
if (!end) end = parseDateDMY(document.getElementById("myDate").value);
var distance = end - now;
// If gone past end, stop the timer
if (distance < 0) {
stopTimer();
document.getElementById('countdown').innerHTML = 'EXPIRED!';
} else {
var months = Math.floor(distance / _month);
var days = Math.floor((distance % _month) / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
// Write the time remaining directly to the element
document.getElementById('countdown').innerHTML = months + 'months ' +
days + 'days ' +
hours + 'hrs ' +
minutes + 'mins ' +
seconds + 'secs';
}
}
// No need to do this, wait for button click
// timer = setInterval(showRemaining, 1000);
// Parse date string in format d/m/y
function parseDateDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Add listener to button
window.onload = function() {
document.getElementById('startButton').addEventListener('click',showRemaining,false);
}
Enter your birthday:<br>
<input type="text" id="myDate" value="21/6/2016">d/m/y<br>
<input type="button" id="startButton" value="Start counting"><br>
<div id="countdown"></div>
You have made quite a few mistakes,
The script loads before the elements load. So, it does not work properly. Always incude scripts at the last or use window.onload = (function() { [Your code] }());. This executes only after the dom loads.
The setInterval function must always execute only if "not EXPIRED!". Keep it within the function so it only runs again if the countdown must go on.
The main problem, you were comparing date strings to 0. You can rather use
Date.now() which returns the total milliseconds from Jan 1, 1970. And use Date("User Input String which you provided") to get the total milliseconds from Jan 1, 1970 till that date and see the difference which is very accurate.
I recommend using separate input boxes or a more formatted input. Read more about these here.
Also try using 'buttonElement.addEventListener("click", showRemaining);`.
This should work:
<body>
<script>
var end = new Date();
document.getElementById("myDate").value = end;
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var _month = _day * 30;
var timer;
function showRemaining() {
var now = Date.now(); //CHANGE
end = new Date(document.getElementById("myDate").value); //CHANGE
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var months = Math.floor(distance / _month);
var days = Math.floor((distance % _month) / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = months + 'months ';
document.getElementById('countdown').innerHTML += days + 'days ';
document.getElementById('countdown').innerHTML += hours + 'hrs ';
document.getElementById('countdown').innerHTML += minutes + 'mins ';
document.getElementById('countdown').innerHTML += seconds + 'secs';
timer = setInterval(showRemaining, 1000); //CHANGE
}
</script>
<!-- CHANGE -->
Enter your birthday:
<br />
<input type="date" id="myDate">
<br /><br />
<input type="button" onclick="showRemaining()" value="Enter">
This snippet fixes your issue. The issue was two-fold.
document.getElementById("myDate").value = end; This statement is reversed. You want need the value of the field to be put into end. This statement also executes immediately, which is of no use. This has been replaced by two things (1) the initDate function, to make the date field have an initial value (if that's what you were trying to do), and (2) the event listener on the button. This way, when the user has selected a date and clicks the button, you know that a value has been set, and can confidently start the timer.
Dates. The date value given by the input you have is in the format YYYY-mm-dd, which needs to be split() on the hyphens to create a new Date() correctly. The Date library can be tricky to work with. When creating dates it can be hard to determine if they're going to be UTC or local. And that issue can screw you up pretty easily, so watch that.
This code should be what you're looking for and should help clarify some of the points you may not have understood when writing the original code. It's not perfect necessarily (due to the fact that a month is hardcoded in as 30 days), but it depends on what you are looking for. Let me know if you have any other questions.
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var _month = _day * 30;
var timer;
initDate();
document.getElementById('startButton').addEventListener("click", function() {
document.getElementById('value').innerHTML = document.getElementById("myDate").value;
var splitValues = document.getElementById("myDate").value.split('-');
var end = new Date(splitValues[0], splitValues[1] - 1, splitValues[2]);
clearInterval(timer);
showRemaining(end);
timer = setInterval(showRemaining, 1000, end);
});
function showRemaining(end) {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var months = Math.floor(distance / _month);
var days = Math.floor((distance % _month) / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = months + 'months ';
document.getElementById('countdown').innerHTML += days + 'days ';
document.getElementById('countdown').innerHTML += hours + 'hrs ';
document.getElementById('countdown').innerHTML += minutes + 'mins ';
document.getElementById('countdown').innerHTML += seconds + 'secs';
}
function initDate() {
var defaultDate = new Date();
var month;
if(defaultDate.getMonth() + 1 > 9) {
month = "" + (defaultDate.getMonth() + 1);
} else {
month = '0' + (defaultDate.getMonth() + 1);
}
document.getElementById("myDate").value = defaultDate.getFullYear() + '-' + month + '-' + defaultDate.getDate();
}
<input id="myDate" type="date">
<button id="startButton">Start Countdown</button>
<div id="value"></div>
<div id='countdown'></div>
I have included the "more accurate" version below, since it was easy to change.
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
initDate();
document.getElementById('startButton').addEventListener("click", function() {
document.getElementById('value').innerHTML = document.getElementById("myDate").value;
var splitValues = document.getElementById("myDate").value.split('-');
var end = new Date(splitValues[0], splitValues[1] - 1, splitValues[2]);
clearInterval(timer);
showRemaining(end);
timer = setInterval(showRemaining, 1000, end);
});
function showRemaining(end) {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').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);
document.getElementById('countdown').innerHTML = days + ' days ';
document.getElementById('countdown').innerHTML += hours + ' hrs ';
document.getElementById('countdown').innerHTML += minutes + ' mins ';
document.getElementById('countdown').innerHTML += seconds + ' secs';
}
function initDate() {
var defaultDate = new Date();
var month;
if (defaultDate.getMonth() + 1 > 9) {
month = "" + (defaultDate.getMonth() + 1);
} else {
month = '0' + (defaultDate.getMonth() + 1);
}
document.getElementById("myDate").value = defaultDate.getFullYear() + '-' + month + '-' + defaultDate.getDate();
}
<input id="myDate" type="date">
<button id="startButton">Start Countdown</button>
<div id="value"></div>
<div id='countdown'></div>

Multiple JavaScript countdown dates?

So I currently have one date, but I want multiple and for them to have unique id's.
I can currently use <div id="countdown"></div> to put it in my html, but I want to do something like id="countdown1", id="countdown2", id="countdown3", etc.
To explain more in depth i'm trying to have several dates like this with unique id's for each one so I can put each individual one in the html.
var end = new Date(Date.UTC(2015, 10, 10));
var end = new Date(Date.UTC(2015, 10, 11));
var end = new Date(Date.UTC(2015, 10, 12));
var end = new Date(Date.UTC(2015, 10, 13));
This is my current script:
var end = new Date(Date.UTC(2015, 10, 10, 5));
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('countdown').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);
document.getElementById('countdown').innerHTML = days + ' Day | ';
document.getElementById('countdown').innerHTML += hours + ' Hours | ';
document.getElementById('countdown').innerHTML += minutes + ' Minutes | ';
document.getElementById('countdown').innerHTML += seconds + ' Seconds ';
}
timer = setInterval(showRemaining, 1000);
I tried a lot of different things and searched many times for a solution but have found nothing. Any help on this would be very appreciated.
Use object, it is a cleaner solution.
function Timer(holder) {
var controller = {
holder: holder,
end: null,
intervalID:0,
display: function () {
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var msg = "";
var now = new Date();
var distance = controller.end - now;
if (distance < 0) {
clearInterval(controller.intervalID);
controller.holder.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);
controller.holder.innerHTML = days + ' Day | ' + hours + ' Hours | ' + minutes + ' Minutes | ' + seconds + ' Seconds ';
}
}
this.countDown = function (end) {
controller.end = end;
controller.intervalID = setInterval(controller.display, 1000);
}
}
Working sample at https://jsfiddle.net/mLr571tj/
EDIT: Make sure you use the same date time format on initialization and in display function.
Try scoping the variables to the function and returning it once it's called. I made an example for you:
http://jsfiddle.net/wt9pb9r3/1/
I use setTimeoutto simulate the dates being initiated a few seconds apart.

Change color depending on remaining time

I were wondering if there was a simple way to change the color on a countdown-timer (I want the color on the timer to change into red once there is less than 12 hours left)
CountDownTimer('09/09/2013 23:59', 'countdown');
CountDownTimer('09/11/2013 15:30', 'countdown2');
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 = '<span class=exp>Utgått!</span>';
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);
document.getElementById(id).innerHTML = days + ' Dager ';
document.getElementById(id).innerHTML += hours + ' Timer ';
document.getElementById(id).innerHTML += minutes + ' Minutter ';
}
timer = setInterval(showRemaining, 1000);
}
This is the code I'm using.
In advance, thank you :)
Simply add the following line:
document.getElementById(id).style.color = days === 0 && hours < 12 ? 'red' : '';
JS Fiddle demo.
Which will set the color of the containing element to 'red' if there are zero days and less than twelve hours left, or set it to nothing (passing an empty string) if there are one, or more, days or twelve, or more, hours left.
Though I would suggest caching the element you're using once and then using that, rather than re-querying the DOM every time:
var cachedEl = document.getElementById(id);
/* all the other stuff... */
cachedEl.innerHTML = days + ' Dager ';
cachedEl.innerHTML += hours + ' Timer ';
cachedEl.innerHTML += minutes + ' Minutter ';
cachedEl.innerHTML += seconds + ' Seconds. ';
cachedEl.style.color = days === 0 && hours < 12 ? 'red' : '';
JS Fiddle demo.

Categories

Resources