Countdown for a specific date - javascript

I want to build a countdown program. But my problem is that I cant get the
getElementsByClassName
to work (in my opinion). The WHOLE program will work if I use
getElementById
and change the HTML tags with id=""...
My whole code is available here: https://jsfiddle.net/f1kzL78h/5/
I need the class-function because I will have more p-tags in the future in my HTML-file, and I want to apply Javascript to all my classes that have the same name.
HTML:
<p class="date">2019-04-13</p>
<p class="time">21:21</p>
<p class="appear"></p>
JS:
var articleDate = document.getElementsByClassName("date");
var articleTime = document.getElementsByClassName("time");
var total = articleDate + 'T' + articleTime + ':00';
var countDownTime = new Date(total).getTime();
var x = setInterval(function() {
var timeNow = new Date().getTime();
var difference = countDownTime - timeNow;
var days = Math.floor(difference / (1000 * 60 * 60 * 24));
var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);
res = days + ":" + hours + ":" + minutes + ":" + seconds;
document.getElementsByClassName("appear") = res;
}, 1000);
I appreciate all help i can get.

Change to document.getElementsByClassName("appear")[0].innerHTML = res;
Also update for
var articleDate = document.getElementsByClassName("date")[0].innerHTML;
var articleTime = document.getElementsByClassName("time")[0].innerHTML;
Because document.getElementsByClassName("appear") only DOM element, and document.getElementsByClassName return array of element, need innerHTML to get value.
https://jsfiddle.net/viethien/8mxh0zkr/3/

Elements by class
document.getElementsByClassName("appear") returns a collection of elements. You can iterate it with the following code
const appears = document.getElementsByClassName("appear");
for (var i = 0; i < appears.length; i++) {
appears.item(i).innerHTML = res;
}
Get dates from HTML
You were using var articleDate = document.getElementsByClassName("date"); which is not returning the expected value
You should use var articleDate = document.getElementsByClassName("date")[0].innerHTML; to get the value inside your element
Implementation in your case
// Fångar upp information om artiklens datum och tid
var articleDate = document.getElementsByClassName("date")[0].innerHTML;
var articleTime = document.getElementsByClassName("time")[0].innerHTML;
var total = articleDate + 'T' + articleTime + ':00';
var countDownTime = new Date(total).getTime();
var x = setInterval(function() {
var timeNow = new Date().getTime();
var difference = countDownTime - timeNow;
var days = Math.floor(difference / (1000 * 60 * 60 * 24));
var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);
res = days + ":" + hours + ":" + minutes + ":" + seconds;
const appears = document.getElementsByClassName("appear");
for (var i = 0; i < appears.length; i++) {
appears.item(i).innerHTML = res;
}
}, 1000);
<p class="date">2019-04-13</p>
<p class="time">21:21</p>
<p class="appear"></p>

Change code like this. Use document.getElementsByClassName("date")[0].textContent for getting value.
// Fångar upp information om artiklens datum och tid
var articleDate = document.getElementsByClassName("date")[0].textContent;
var articleTime = document.getElementsByClassName("time")[0].textContent;
var total = articleDate + 'T' + articleTime + ':00';
var countDownTime = new Date(total).getTime();
var x = setInterval(function() {
var timeNow = new Date().getTime();
var difference = countDownTime - timeNow;
var days = Math.floor(difference / (1000 * 60 * 60 * 24));
var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);
res = days + ":" + hours + ":" + minutes + ":" + seconds;
document.getElementsByClassName("appear")[0].textContent = res;
}, 1000);
<p class="date">2019-04-13</p>
<p class="time">21:21</p>
<p class="appear"></p>

"I need the class-function because I will have more p-tags in the
future in my HTML-file, and I want to apply Javascript to all my
classes that have the same name."
I did a little modification to give you an idea. I think this can be your start point to create a countdown for many elements:
<p class="date">2019-04-13</p>
<p class="time">21:21</p>
<p class="appear"></p>
<p class="date">2019-04-13</p>
<p class="time">10:21</p>
<p class="appear"></p>
setInterval(function() {
var articleElements = document.getElementsByClassName("date");
for(var i = 0; i < articleElements.length; i++) {
var articleDate = articleElements[i].innerText;
var articleTime = articleElements[i].nextElementSibling.innerText;
var total = articleDate + 'T' + articleTime + ':00';
var countDownTime = new Date(total).getTime();
var elAppear = articleElements[i].nextElementSibling.nextElementSibling;
elAppear.setAttribute('data-countdown', countDownTime);
var timeNow = new Date().getTime();
var difference = countDownTime - timeNow;
var days = Math.floor(difference / (1000 * 60 * 60 * 24));
var hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((difference % (1000 * 60)) / 1000);
res = days + ":" + hours + ":" + minutes + ":" + seconds;
elAppear.innerText = res;
}
}, 1000);

Related

jQuery/Javascript make callback for countdown

I have jquery countdown function with below code:
$.fn.countdown = function(toTime, callback){
let $el = $(this);
var intervalId;
let timeUpdate = () => {
var now = new Date().getTime();
var distance = toTime - now;
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(distance < 0){
clearInterval(intervalId);
}
else{
var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
$el.html(value);
}
if(callback) callback();
}
timeUpdate();
intervalId = setInterval(timeUpdate, 1000);
};
$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime());
$('#my_div2').countdown(new Date("Jun 23, 2022 22:20:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>
Now I need to add callback function if the time has finished.
My idea is like this:
$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime(), function(){
callback: function() {
alert("Counting Finish");
}
});
Is there any way to implement that callback?
Your code is almost there, there's just two issues. Firstly you need to invoke the callback argument from within the distance < 0 block, as that's what determines when the countdown has ended. Secondly you need to provide an actual callback argument to the countdown() call.
Note in the following example I made the countdowns only a few seconds from the current date to make the demo clearer.
$.fn.countdown = function(toTime, callback) {
let $el = $(this);
var intervalId;
let timeUpdate = () => {
var now = new Date().getTime();
var distance = toTime - now;
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 (distance < 0) {
clearInterval(intervalId);
callback && callback();
} else {
var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
$el.html(value);
}
}
timeUpdate();
intervalId = setInterval(timeUpdate, 1000);
};
var date1 = new Date();
date1.setSeconds(date1.getSeconds() + 5);
$('#my_div').countdown(date1.getTime(), () => console.log('first countdown elapsed!'));
var date2 = new Date();
date2.setSeconds(date2.getSeconds() + 10);
$('#my_div2').countdown(date2.getTime(), () => console.log('second countdown elapsed!'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>

Countdown timer in Javascript shows the old data too after new data is entered

So here I am writing a countdown timer with HTML and Javascript. But I am having an issue with it. It looks like it doesn't ''forget'' the old input data and shows both old and new almost at the same time after I click the Calculate button.
My code seems to work but the problem is that when I enter a new date it shows both old and new timer. For example, if I enter December 7, 2020 it will show 1 day (some minutes and seconds, whatever) and after that if I enter December 8, 2020 within each second it shows 2 days and then it suddenly changes to 1 day then changes to 2 days etc. If I enter another date it will quickly show all three timers. how do I fix this?
I thought that the old information was left and I tried adding a statement to clear the "res" part but it still does the same. I don't know what is the reason.
function calculate() {
var until_date = new Date(document.getElementById("input_date").value).getTime();
var x = setInterval(function() {
var today = new Date().getTime();
var d = until_date - today;
var days = Math.floor(d / (1000 * 60 * 60 * 24));
var hr = Math.floor((d % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var min = Math.floor((d % (1000 * 60 * 60)) / (1000 * 60));
var sec = Math.floor((d % (1000 * 60)) / 1000);
document.getElementById("res").innerHTML = days + "d " + hr + "h " + min + "m " + sec + "s ";
if (d < 0) {
clearInterval(x);
document.getElementById("res").innerHTML = "DONE";
}
}, 1000);
}
<p>Please select a date: <input id="input_date" type="date"></p>
<button id='calulate' onclick="calculate()">Calculate</button>
<p id="res"></p>
Just put the interval variable outside the function and clear the interval when the function is called again outside the loop.
Otherwise each function call you will be creating a new interval which will run parallel to the previous one.
var x;
function calculate() {
clearInterval(x);
var until_date = new Date(document.getElementById("input_date").value).getTime();
x = setInterval(function () {
var today = new Date().getTime();
var d = until_date - today;
var days = Math.floor(d / (1000 * 60 * 60 * 24));
var hr = Math.floor((d % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var min = Math.floor((d % (1000 * 60 * 60)) / (1000 * 60));
var sec = Math.floor((d % (1000 * 60)) / 1000);
document.getElementById("res").innerHTML = days + "d " + hr + "h " + min + "m " + sec + "s ";
if (d < 0) {
clearInterval(x);
document.getElementById("res").innerHTML = "DONE";
}
}, 1000);
}

Pure JS countdown timer

I am trying to create a countdown timer, when i click on a button the timer will run according to the value 5, 15, 30 .
I could create a timer but my problem when using the set interval is i can't pass argument to the callback function, when i run the callback function with a preset value it runs fine, but when i am passing an argument it crashes,
var currentTime = new Date();
function displayCurrentTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var display = document.getElementById('now');
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
return(new Date().getTime());
}
setInterval(displayCurrentTime, 1000);
function endTime(m) {
var display = document.getElementById('endTime');
var endingTime = new Date(currentTime.getTime() + (m * 60 * 1000));
var hours = endingTime.getHours();
var minutes = endingTime.getMinutes();
var seconds = endingTime.getSeconds();
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
return endingTime.getTime();
}
function counter() {
var display = document.getElementById('counter');
var countingTime = endTime(1) - displayCurrentTime();
var days = Math.floor(countingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((countingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((countingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((countingTime % (1000 * 60)) / 1000);
return (display.innerHTML = (hours + '.' + minutes + '.' + seconds));
}
<button id="5" onclick="setInterval(counter, 1000)">5</button>
<button id="15" onclick="setInterval(counter, 1000)">15</button>
<button id="30" onclick="setInterval(counter, 1000)">30</button>
<h3>Current Time</h3>
<p id="now"></p>
<h3>Your time will end at</h3>
<p id="endTime"></p>
<h3>You still have</h3>
<p id="counter"></p>
You can pass any arguments that you want after the delay param in the setInterval. Eg. setInterval(foo, 1000, bar). bar will be passed as a argument to foo every second.
I would simply set the end-time on click and start the counter. So your counter
var endTime = null;
function displayCurrentTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var display = document.getElementById('now');
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
//just call counter here if endTime is set. in this case you only need to call updateEndTime on click
//if(endTime != null) {
// counter();
//}
}
//to avoid 1 second delay on start up
displayCurrentTime()
setInterval(displayCurrentTime, 1000);
function updateEndTime(m) {
var display = document.getElementById('endTime');
var currentTime = new Date();
endTime = new Date(currentTime.getTime() + (m * 60 * 1000));
var hours = endTime.getHours();
var minutes = endTime.getMinutes();
var seconds = endTime.getSeconds();
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
}
function counter() {
var display = document.getElementById('counter');
var currentTime = new Date();
var countingTime = endTime - currentTime;
var days = Math.floor(countingTime / (1000 * 60 * 60 * 24));
var hours = Math.floor((countingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((countingTime % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((countingTime % (1000 * 60)) / 1000);
display.innerHTML = (hours + '.' + minutes + '.' + seconds);
}
<button id="5" onclick="updateEndTime(5);counter();setInterval(counter, 1000)">5</button>
<button id="15" onclick="updateEndTime(15);counter();setInterval(counter, 1000)">15</button>
<button id="30" onclick="updateEndTime(30);counter();setInterval(counter, 1000)">30</button>
<h3>Current Time</h3>
<p id="now"></p>
<h3>Your time will end at</h3>
<p id="endTime"></p>
<h3>You still have</h3>
<p id="counter"></p>
Btw. you probably should only use 1 setInterval and update both counters in 1 call checking if endTime is set or not

Countdown timer expires start a different countdown

I have the following code. I want when this timer expires, another timer should start instead of expired text.
var countDownDate = new Date("Oct 25, 2017 15:37:25").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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);
document.getElementById("demo").innerHTML = days + " Days " + hours + " Hrs "
+ minutes + " Min " + seconds + " Sec ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "T**imer Expired - instead of this another timer**";
}
}, 1000);
Create a function, and call it every time the timer is finished.
$(document).ready(function() {
var i = 1 ;
setTimer(i) ;
}) ;
function setTimer(i) {
var countDownDate = new Date().getTime() + 3000 ;
var x = setInterval(function() {
var now = new Date().getTime() ;
var distance = countDownDate - now ;
if (distance < 0) {
clearInterval(x);
console.log("Timer " + i + " Finished. New Timer Stated!") ;
setTimer(i+1) ;
}
else {
console.log("Timer " + i + " Running") ;
}
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This code should do the trick. Each time the counter get to 0, you redefined your count down to the same amount of time there was initially between countDownDate and Now. If this amount is variable, you might modify the assignment of distanceToAdd
// Changed the value to reach for the demo
var countDownDate = new Date().getTime() + 20000;
// Fixed Value to add each time the counter get to 0
var distanceToAdd = countDownDate - new Date().getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var distance = countDownDate - now;
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 (distance < 0) {
//Add Time to your timer goal instead of canceling interval
countDownDate += distanceToAdd;
}
else {
document.getElementById("demo").innerHTML = days + " Days " + hours + " Hrs "
+ minutes + " Min " + seconds + " Sec ";
}
}, 1000);
<html>
<head>
</head>
<body>
<div id="demo"></div>
</body>
</html>

Execute code from text input in countdown function

In the following code I want to make a text input field (for a date) which gets executed so that the countdown timer is set to that value and starts counting - for example after clicking "OK" button. I don't really know how to modify the first variable in order to do that.
<script>
// Set the date we're counting down to
var countDownDate = new Date("May 25, 2018 11:30: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="demo"
document.getElementById("demo").innerHTML = "Pozostało: </br>" + days + " Dni, </br>" + hours + "g : " + minutes + "m : " + seconds + "s";
document.getElementById("demo").style.fontSize = "45px";
document.getElementById("demo").style.fontWeight = "bold";
document.getElementById("demo").style.color = "white";
document.getElementById("demo").style.backgroundColor = "#4783bf";
document.getElementById("demo").style.textAlign ="center";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Thank you for all the advice!
Have a look at this fiddle start timer on click of button
I have entered this date in textbox :- May 26, 2017 01:30:00
function startTimer(){
var dateEntered = document.getElementById("txtDate").value;
// Set the date we're counting down to
//May 26, 2017 01:30:00
var countDownDate = new Date(dateEntered).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="demo"
document.getElementById("demo").innerHTML = "Pozostało: </br>" + days + " Dni, </br>" + hours + "g : " + minutes + "m : " + seconds + "s";
document.getElementById("demo").style.fontSize = "45px";
document.getElementById("demo").style.fontWeight = "bold";
document.getElementById("demo").style.color = "white";
document.getElementById("demo").style.backgroundColor = "#4783bf";
document.getElementById("demo").style.textAlign ="center";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
<input type="text" id="txtDate"/>
<br>
<input type="button" value="Calculate" onclick="startTimer();">
<div id="demo">
</div>
The first, you need to download datetimepicker library.
https://plugins.jquery.com/datetimepicker/
And then, following this. Remember to change the path of css and jquery files.
<link href="~/css/jquery.datetimepicker.css" rel="stylesheet" />
<body>
<input type="text" id="datetimepicker" />
<input type="button" value="Ok" id="btOk" />
<p id="demo" />
</body>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/jquery.datetimepicker.min.js"></script>
<script type="text/javascript">
$('#datetimepicker').datetimepicker();
$(document).ready(function () {
$('#btOk').click(function () {
var currentDate = $('#datetimepicker').val();
var countDownDate = new Date(currentDate).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="demo"
document.getElementById("demo").innerHTML = "Pozostało: </br>" + days + " Dni, </br>" + hours + "g : " + minutes + "m : " + seconds + "s";
document.getElementById("demo").style.fontSize = "45px";
document.getElementById("demo").style.fontWeight = "bold";
document.getElementById("demo").style.color = "white";
document.getElementById("demo").style.backgroundColor = "#4783bf";
document.getElementById("demo").style.textAlign = "center";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
});
});
</script>

Categories

Resources