Given this HTML:
<span class="countdown-date" data-countdown-date="2020-08-31 18:00:00"></span>
<span class="countdown-date" data-countdown-date="2020-12-31 00:00:00"></span>
I am trying to display the value of data-countdown-date attribute as countdown text in the span using this JS:
document.addEventListener('DOMContentLoaded', function () {
var list = document.getElementsByClassName('countdown-date');
for (let item of list) {
// console.log(item.getAttribute("data-countdown-date"));
// shows 2020-08-31 18:00:00 and 2020-12-31 00:00:00.
// Set the date we're counting down to
var countDownDate = new Date(item.getAttribute("data-countdown-date")).getTime();
// console.log(countDownDate);
// shows 1598860800000 and 1609333200000
// 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
// console.log(days);
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);
// Display the result in the element with id="countdown-date"
item.innerHTML =
days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's ';
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
item.innerHTML = 'EXPIRED';
}
}, 1000);
};
});
The problem is that both the countdown dates keep showing the same values.
Like this: 136d 1h 56m 26s (initial value when the page is loaded).
Any help would be appreciated.
source for the JS code: https://www.w3schools.com/howto/howto_js_countdown.asp.
countDownDate needs to be declared inside the interval function.
When it's declared outside the variable is overwritten.
document.addEventListener('DOMContentLoaded', function () {
var list = document.getElementsByClassName('countdown-date');
for (let item of list) {
// console.log(item.getAttribute("data-countdown-date"));
// shows 2020-08-31 18:00:00 and 2020-12-31 00:00:00.
// console.log(countDownDate);
// shows 1598860800000 and 1609333200000
// Update the count down every 1 second
var x = setInterval(function () {
// Set the date we're counting down to
var countDownDate = new Date(item.getAttribute("data-countdown-date")).getTime();
// 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
// console.log(days);
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);
// Display the result in the element with id="countdown-date"
item.innerHTML =
days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's ';
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
item.innerHTML = 'EXPIRED';
}
}, 1000);
};
});
<span class="countdown-date" data-countdown-date="2020-08-31 18:00:00"></span>
<span class="countdown-date" data-countdown-date="2020-12-31 00:00:00"></span>
document.addEventListener('DOMContentLoaded', function () {
var list = document.getElementsByClassName('countdown-date');
function processdate(countDownDate, item) {
// 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
// console.log(days);
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);
// Display the result in the item
item.innerHTML =
days + 'd ' + hours + 'h ' + minutes + 'm ' + seconds + 's ';
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
item.innerHTML = 'EXPIRED';
}
}
for (let item of list) {
// Set the date we're counting down to
var countDownDate = new Date(item.getAttribute("data-countdown-date")).getTime();
// Update the count down every 1 second
var x = setInterval(processdate, 1000, countDownDate, item);
}
});
Related
I am using the following code to:
Show the remaining time for an "X" event.
Print text when that event is> 0.
Calculate 2 hours of event duration and print something else.
I love how this works, but I want that when the event ends, the counter automatically prints the remaining time for the same event the next day.
// Set the date we're counting down to
// Year, Month ( 0 for January ), Day, Hour, Minute, Second, , Milliseconds
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::: 4:00 PM ::::::::::::
//:::::::::::: ::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// (AAAA, MM, DD, HH, mm, S ));
var countDownDate = new Date(Date.UTC(2021, 07, 16, 23, 00, 00));
function chiriTimer() {
// 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 an the count down date
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Output the result in an element with id="demo"
for (const ele of document.getElementsByClassName("chiriTimer")){
ele.innerHTML = (days + "<span>d</span> " + hours + "<span>h</span> "
+ minutes + "<span>m</span> " + seconds + "<span>s</span><br />")
}
// If the count down is over, write some text
if (distance < 0) {
for (const ele of document.getElementsByClassName("chiriTimer")) {
ele.innerHTML = "<p class='live-text'>En Vivo <i class='fa fa-circle faa-flash animated'></i></p> ";
}
if (distance + 7200000 < 0) {
for (const allEllements of document.getElementsByClassName("chiriTimer")) {
allEllements.innerHTML = "Finalizó";
}
}
}
}, 1000);
}
chiriTimer()
<p class="chiriTimer"></p>
To repeat the countdown for the next day three hours after the current countdown is over. Before the code that checking for two hours due, check for three hours due first distance + 10800000 < 0, then change the countDownDate to the next date.
function chiriTimer() {
// 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 an the count down date
// GMT/UTC Adjustment at the end of the function. 0 = GMT/UTC+0; 1 = GMT/UTC+1.
var distance = countDownDate - now - (3600000 * 1);
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Output the result in an element with id="demo"
for (const ele of document.getElementsByClassName("chiriTimer")){
ele.innerHTML = (days + "<span>d</span> " + hours + "<span>h</span> "
+ minutes + "<span>m</span> " + seconds + "<span>s</span><br />")
}
// If the count down is over, write some text
if (distance < 0) {
for (const ele of document.getElementsByClassName("chiriTimer")) {
ele.innerHTML = "<p class='live-text'>En Vivo <i class='fa fa-circle faa-flash animated'></i></p> ";
}
if (distance + 10800000 < 0) {
countDownDate = new Date(countDownDate.getTime() + 86400000)
} else if (distance + 7200000 < 0) {
for (const allEllements of document.getElementsByClassName("chiriTimer")) {
allEllements.innerHTML = "Finalizó";
}
}
}
}, 1000);
}
I'm trying to have a simple countdown timer that converts a time given on a page to a countdown.
It works, but my current issue is how the normal date is shown and then later it's parsed by the JavaScript. I want it parsed by JS right away so a user doesn't see it flicking between the date and the countdown timer.
It converts this to the countdown:
<span class="countdown">12/10/20 13:10:00</span>
This is the code:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).text();
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
// Update the count down every 1 second
var x = setInterval(function()
{
// Get today's 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="demo"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
}, 1000);
});
}
What I am asking for, is suggestions on how to get around this problem. Is the only way to have it loaded before the HTML or what? I'm confused on the best practices for this. Everywhere keeps telling me to defer JavaScript loading...but what about stuff like this that changes the content?
In cases like this, is it a good idea to have a "core" file for content-changing stuff that loads right away, then the rest after the content or what?
The problems comes from setInterval not executing automatically , which is normal. Here's a work around it:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).text();
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
var counterFunction = function()
{
// Get today's 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="demo"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
return counterFunction;
}
// Update the count down every 1 second
var x = setInterval(counterFunction(), 1000);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="countdown">12/10/20 13:10:00</span>
I suggest to put the date in data-date attr, like this:
<span data-date="12/10/20 13:10:00" class="countdown"></span>
than the script:
if ($('.countdown').length)
{
$.each( $('.countdown'), function( key, value )
{
var time_listed = $(value).attr("data-date");
var countdown_object = $(value);
// Set the date we're counting down to
var countDownDate = new Date(time_listed).getTime();
// Update the count down every 1 second
var x = setInterval(function()
{
// Get today's 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 days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="demo"
countdown_object.text (days + " days " + hours + "h "
+ minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0)
{
clearInterval(x);
countdown_object.text("EXPIRED");
}
}, 1000);
});
}
https://jsfiddle.net/750o1neh/
I have build a popup with a timer. When the timer ends I want it to extend itself with another day. I have gone so far that it extends itself with 1 day for 1 time but then it quits.
Maybe you have any idea on how to proceed?
Thanks!
//Make countdown
var setInfiniteTime = '{{ $actiepopup->infiniteTime }}';
// Update the count down every 1 second
var x = setInterval(function() {
// Set the date we're counting down to
// Get todays date and time
var currentDate = new Date().getTime();
// get countdown time
var countDownDate = new Date(countDownTimeUntil).getTime();
// console.log('countdowndateBefore' + countDownDate);
// check in infinite time is set
if (setInfiniteTime == 'Yes') {
if (currentDate >= countDownDate) {
// var i;
// for (var i = 0; i < 999999; i++) {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000;
// console.log(i);
// }
}
}
// console.log('currentdate' + currentDate);
// console.log('countdowndate' + countDownDate);
// Find the distance between now and the count down date
var distance = countDownDate - currentDate;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="countdown"
$("#countdown").text(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
$("#countdown").text("Actie beeïndigd");
}
}, delayInMilliseconds);
Hope you have enough information!
SetInterval()
Also, just an advice, if you use boolean statements, just use true or false since it's way easier to work with
if (setInfiniteTime) {
setInterval(() => {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000
}, 86400000)
}
I'm trying to convert the 0 in stock text on my website (held within a <p> tag) to a countdown timer, once the stock level hits 0. So I've added this code to the footer - however it seems to just stick, and not count down at all. It also takes a few seconds to replace the 0 in stock text - can I make this quicker/instant? Here's the code so far:
// Set the count down date
var countDownDate = new Date("Feb 21, 2021 15:26:00").getTime();
// Update the count every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result if stock = 0
list = document.getElementsByClassName("stock in-stock");
if (list[0].innerHTML == "0 in stock") {
list[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
// If the count down is finished, write text
if (distance < 0) {
clearInterval(x);
list = document.getElementsByClassName("stock in-stock");
list[0].innerHTML = "Item expired!";
}
}, 1000);
<p class="stock in-stock">1 in stock</p>
You were trying to populate the P with new data and somehow trying to read out the old data, I've just separated that into 2 spans so you can work with each one individually and updated your JS to reflect the new structure.
To speed up the first call, extract the function:
Please note that we're treating "stock" and "countdown" as 2 different things now.
// Set the count down date
var countDownDate = new Date("Feb 21, 2021 15:26:00").getTime();
function ctd() {
// Get today's date and time
var now = new Date().getTime();
// Distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
//console.log(days + " " + hours + " " + minutes + " " + seconds);
// Display the result if stock = 0
countdown = document.getElementsByClassName("countdown");
stock = document.getElementsByClassName("stock-level");
if (stock[0].innerHTML == "1") {
countdown[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
// If the count down is finished, write text
if (distance < 0) {
clearInterval(x);
countdown.innerHTML = "Item expired!";
}
}
ctd(); // run now
// Update the count every 1 second
var x = setInterval(ctd, 1000);
<p class="stock-level" style="display:none">1</p>
<p class="countdown"></p>
I got it to work. Here's the code:
<script>
//Set the count down date
var countDownDate = new Date("Feb 20, 2019 18:26:00").getTime();
var startTimer=false;
list = document.getElementsByClassName("stock in-stock");
if(list[0].innerHTML=='1 in stock') {
startTimer=true;
}
//Check if 1 left
list = document.getElementsByClassName("stock in-stock");
//Update the count every 1 second
var x = setInterval(function() {
//Get today's date and time
var now = new Date().getTime();
//Distance between now and the count down date
var distance = countDownDate - now;
//Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
//Update the counter
if(startTimer) {
list[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}
//If the count down is finished, write text
if (distance < 0) {
clearInterval(x);
list = document.getElementsByClassName("stock in-stock");
list[0].innerHTML = "Item expired!";
}
}, 1000);
</script>
I'm using the following JavaScript for a countdown timer and it has been working great in most browsers, I've just double checked Internet Explorer however and I am getting 'NaN' displayed in place of each number.
Can anyone help to explain where this goes wrong in IE not seeing the individual variables as a number?
// Set the date we're counting down to
var countDownDate = new Date("2018-05-25 12:00:00").getTime();
// 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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
if (days.toString().length < 2) {
days = "0" + days;
}
if (hours.toString().length < 2) {
hours = "0" + hours;
}
if (minutes.toString().length < 2) {
minutes = "0" + minutes;
}
if (seconds.toString().length < 2) {
seconds = "0" + seconds;
}
// Display the result in the element with id="countdown"
document.getElementById("countdown").innerHTML = days + " : " + hours + " : " +
minutes + " : " + seconds;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>
MDN discourages the use of a string in the date constructor because not all browsers implement this the same way.
If you do want to use date strings, I would recommend using a third party library like momentjs to parse these strings to make sure this works in every browser.
Just normalise the date and time
function getNormalisedDatetime(dString) { // yyyy-mm-dd hh:mm:ss
var parts = dString.split(" ");
var dParts = parts[0].split("-");
var tParts = parts[1].split(":");
return new Date(dParts[0],dParts[1]-1,dParts[2],tParts[0],tParts[1],tParts[2]);
}
function pad(num) {
return ("0"+num).slice(-2);
}
// Set the date we're counting down to
var countDownDate = getNormalisedDatetime("2018-05-25 12:00:00").getTime();
// 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 an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
// Display the result in the element with id="countdown"
document.getElementById("countdown").innerHTML = "" + pad(days) + " : " + pad(hours) + " : " +
pad(minutes) + " : " + pad(seconds);
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>