I have a count down clock on my site but it resets if you clear your browser history. Is there a way to stop this from happening. I found the code on a website that you can download from. I was not expecting it to reset when you clear your browser history. Can this code be modified or would it be better for me to find another code for it.
Thanks
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
#clockdiv {
color: #ffffff;
display: inline-block;
font-size: 14px;
font-weight: 100;
text-align: center;
}
#clockdiv > div {
background: #0294cb;
border-radius: 3px;
display: inline-block;
padding: 8px;
}
#clockdiv div > span {
background: #42baff;
border-radius: 3px;
display: inline-block;
padding: 15px;
}
.smalltext {
font-size: 14px;
padding-top: 5px;
}
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
You can save the initial deadline time in localStorage(But this will get cleared on erasing history) and then use that instead of resetting it again on reload, If you want your timer to not reset when clearing data, you will have to maintain a server side state.
You can add this piece of code to the bottom of your script. Instead of initializing new deadline each time, you check whether the deadline has already been initialized and stored in localStorage, if so then fetch the deadline from it. If no, the create the new deadline like you did in your original code and store it in localStorage.
Note that you need to use JSON.stringify and JSON.parse methods if you want to store and later retrieve an object from localStorage because it can only hold strings and default string representation of an object isn't very useful.
This code will not reset the countdown on page reload and you can clean history as well but you can't clear localStorage (cached files and cookies) for it to work.
if (!localStorage.getItem('deadline')) {
const deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
localStorage.setItem('deadline', JSON.stringify(deadline));
initializeClock('clockdiv', deadline);
} else {
const deadline = JSON.parse(localStorage.getItem('deadline'));
initializeClock('clockdiv', deadline);
}
See the snippet for full code, but note that it will not work here because localStorage is not accessible on SO. You will need to copy and paste it and test it in your browser.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
if (!localStorage.getItem('deadline')) {
const deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
localStorage.setItem('deadline', JSON.stringify(deadline));
initializeClock('clockdiv', deadline);
} else {
const deadline = JSON.parse(localStorage.getItem('deadline'));
initializeClock('clockdiv', deadline);
}
#clockdiv {
color: #ffffff;
display: inline-block;
font-size: 14px;
font-weight: 100;
text-align: center;
}
#clockdiv > div {
background: #0294cb;
border-radius: 3px;
display: inline-block;
padding: 8px;
}
#clockdiv div > span {
background: #42baff;
border-radius: 3px;
display: inline-block;
padding: 15px;
}
.smalltext {
font-size: 14px;
padding-top: 5px;
}
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
Related
Helloooo...I've been tasked with creating a web page that contains a count down clock. I have managed to create the clock with HTML and Javascript but what I am having trouble with is the formatting. The client wants the days, hours and minutes in separate individual circles. Not animated, just plain. I've tried a few things with no results. I thought maybe if I created a separate clock for the Days, hours and minutes, that that would work, but when I do this, the clocks disappear. Would love some advice. Thanks a million.
The code for the clock I used is as follows:
<script>
var countDownDate = new Date("Feb 14, 2021 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 + "d " + hours + "h "
+ minutes + "m ";
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "We Are Live!";
}
}, 1000);
</script>
The CSS I used is as follows but I can only get that to work when I just have one time from the clock, like just the days for instance.
.demo{
border-radius: 50%;
width: 50px;
height: 50px;
padding: 10px;
background: #fff;
border: 3px solid #000;
color: #000;
text-align: center;
font: 30px cantata;
display: flex; /* or inline-flex */
align-items: center;
justify-content: center;
}
</style>
Just place the hours, minutes, and seconds within their own containers and style them separately, e.g:
<div id="demo">
<span id="hours"/>:
<span id="minutes"/>:
<span id="seconds"/>
</div>
I'm trying to use this countdown in a wordpress page:
https://codepen.io/varzin/pen/rFfhH
It works on, but I need to use it several times in the same page.
document.getElementById("timer")
I tried to change to document.getElementsbyClassName("timer") but it didn't work.
Am I missing something?
function updateTimer() {
future = Date.parse("June 11, 2021 11:30:00");
now = new Date();
diff = future - now;
days = Math.floor(diff / (1000 * 60 * 60 * 24));
hours = Math.floor(diff / (1000 * 60 * 60));
mins = Math.floor(diff / (1000 * 60));
secs = Math.floor(diff / 1000);
d = days;
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
document.getElementById("timer")
.innerHTML =
'<div>' + d + '<span>days</span></div>' +
'<div>' + h + '<span>hours</span></div>' +
'<div>' + m + '<span>minutes</span></div>' +
'<div>' + s + '<span>seconds</span></div>';
}
setInterval('updateTimer()', 1000);
body {
text-align: center;
padding: 70px 50px;
background: #0D1A29;
font-family: "Helvetica Neue", "Open Sans", helvetica, arial, sans-serif;
}
#timer {
font-size: 3em;
font-weight: 100;
color: white;
text-shadow: 0 0 20px #48C8FF;
div {
display: inline-block;
min-width: 90px;
span {
color: #B1CDF1;
display: block;
font-size: .35em;
font-weight: 400;
}
}
}
<div id="timer"></div>
You need use Array of elements, and foreach element change text.
But better create Class or function for specify future
Your demo with array of timers:
https://codepen.io/Nekiy2/pen/NWNRgPz
function updateTimer() {
future = Date.parse("June 11, 2020 11:30:00");
now = new Date();
diff = future - now;
days = Math.floor(diff / (1000 * 60 * 60 * 24));
hours = Math.floor(diff / (1000 * 60 * 60));
mins = Math.floor(diff / (1000 * 60));
secs = Math.floor(diff / 1000);
d = days;
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
let timers = document.querySelectorAll('.timer')
timers.forEach((e) => { // array of timers
e.innerHTML =
'<div>' + d + '<span>days</span></div>' +
'<div>' + h + '<span>hours</span></div>' +
'<div>' + m + '<span>minutes</span></div>' +
'<div>' + s + '<span>seconds</span></div>';
})
}
setInterval('updateTimer()', 1000);
body {
text-align: center;
padding: 70px 50px;
background: #0D1A29;
font-family: "Helvetica Neue", "Open Sans", helvetica, arial, sans-serif;
}
.timer {
font-size: 3em;
font-weight: 100;
color: white;
text-shadow: 0 0 20px #48C8FF;
div {
display: inline-block;
min-width: 90px;
span {
color: #B1CDF1;
display: block;
font-size: .35em;
font-weight: 400;
}
}
}
<div class="countdown timer"></div>
<div class="countdown timer"></div>
I made a working example with `querySelectorAll() and looping over it.
Note: You also need to change the id of the div to a class and de id selector in the css to a class selector.
function updateTimer() {
console.log()
future = Date.parse("June 11, 2020 11:30:00");
now = new Date();
diff = future - now;
days = Math.floor(diff / (1000 * 60 * 60 * 24));
hours = Math.floor(diff / (1000 * 60 * 60));
mins = Math.floor(diff / (1000 * 60));
secs = Math.floor(diff / 1000);
d = days;
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
document.querySelectorAll('.timer').forEach((el) => {
el.innerHTML =
'<div>' + d + '<span>days</span></div>' +
'<div>' + h + '<span>hours</span></div>' +
'<div>' + m + '<span>minutes</span></div>' +
'<div>' + s + '<span>seconds</span></div>';
});
}
setInterval('updateTimer()', 1000);
body {
text-align: center;
padding: 70px 50px;
background: #0D1A29;
font-family: "Helvetica Neue", "Open Sans", helvetica, arial, sans-serif;
}
.timer {
font-size: 3em;
font-weight: 100;
color: white;
text-shadow: 0 0 20px #48C8FF;
div {
display: inline-block;
min-width: 90px;
span {
color: #B1CDF1;
display: block;
font-size: .35em;
font-weight: 400;
}
}
}
<div class="timer"></div>
<br>
<div class="timer"></div>
You can get the value from the divs
This code allows different timers on the page
Put the same time on all divs to get the same timer
function updateTimer() {
[...document.querySelectorAll(".timer")].forEach(timer => {
const future = Date.parse(timer.getAttribute("data-future"));
const now = new Date();
const diff = future - now;
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
const hours = Math.floor(diff / (1000 * 60 * 60));
const mins = Math.floor(diff / (1000 * 60));
const secs = Math.floor(diff / 1000);
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
timer.innerHTML = `<div>${days}<span>day${days===1?"":"s"}</span></div>
<div>${h}<span>hour${h===1?"":"s"}</span></div>
<div>${m}<span>minute${m===1?"":"s"}</span></div>
<div>${s}<span>second${s===1?"":"s"}</span></div>`;
})
}
setInterval('updateTimer()', 1000);
body {
text-align: center;
padding: 70px 50px;
background: #0D1A29;
font-family: "Helvetica Neue", "Open Sans", helvetica, arial, sans-serif;
}
.timer {
font-size: 3em;
font-weight: 100;
color: white;
text-shadow: 0 0 20px #48C8FF;
div {
display: inline-block;
min-width: 90px;
span {
color: #B1CDF1;
display: block;
font-size: .35em;
font-weight: 400;
}
}
}
<div class="timer" data-future="June 11, 2021 11:30:00"></div>
<hr/>
<div class="timer" data-future="May 2, 2021 14:30:00"></div>
When working with selection by class name, here is what #CBroe was trying to say:
Array.from(document.getElementsByClassName("timer")).forEach(el => {
el.innerHTML =
'<div>' + d + '<span>days</span></div>' +
'<div>' + h + '<span>hours</span></div>' +
'<div>' + m + '<span>minutes</span></div>' +
'<div>' + s + '<span>seconds</span></div>' ;
});
I am building a deal page with countdown timer to show how much time is remaining to claim the offer. I have the countdown timer working to show how many days, hours, minutes and seconds are left, but would like to have a visual progress bar under the time that fills up based on the days left.
For example, the offer goes live July 1 and expires July 31. If the user loads the page on July 1, the progress bar would be at 0%. On July 31, the progress bar would be set to 100%.
I am currently using the progress bar styling and HTML code used by Bootstrap 3.
I've been trying to the width style property for "progress-bar" to the days remaining, but have not been able to get them to link up
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {clearInterval(timeinterval); } } updateClock(); var timeinterval=setInterval(updateClock, 1000); } var deadline=new Date("july 31, 2019 23:59:59"); initializeClock('clockdiv', deadline);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="clockdiv" style="font-weight:600;text-transform: uppercase">Time Remaining:<span class="days"></span>:<span class="hours"></span>:<span class="minutes"></span>:<span class="seconds"></span></div>
<div class="progress" style="margin-bottom:8px;border-radius: 4px">
<div class="progress-bar progress-bar-striped active" style="width:%;border-radius: 4px">
</div>
</div>
Here is a working demo using
Math.round(((today - start) / (end - start)) * 100) + '%';
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime, starttime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
var $progress = $('.progress-bar')
function updateClock() {
var t = getTimeRemaining(endtime);
var p = Math.round(((new Date() - starttime) / (endtime - starttime)) * 100) + '%';
$progress.css('width', p);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var starttime = new Date("july 1, 2019 23:59:59");
var deadline = new Date("july 31, 2019 23:59:59");
initializeClock('clockdiv', deadline, starttime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div id="clockdiv" style="font-weight:600;text-transform: uppercase">Time Remaining:<span class="days"></span>:<span class="hours"></span>:<span class="minutes"></span>:<span class="seconds"></span></div>
<div class="progress" style="margin-bottom:8px;border-radius: 4px">
<div class="progress-bar progress-bar-striped active" style="width:%;border-radius: 4px">
</div>
</div>
Note: It is not necessary to update progress bar every second, It's fine in minutes
You can use document.querySelector('.progress-bar') and then use .style.width = 'xx %' to set the width.
I've refactored the code a bit to make it more readable :)
Working example:
function Clock(id, startDate, endDate) {
this.clock = document.getElementById(id);
this.timeEl = this.clock.querySelector('.time');
this.progressEl = this.clock.querySelector('.progress-bar');
this.startDate = startDate;
this.endDate = endDate;
this.updateClock();
this.interval = setInterval(this.updateClock.bind(this), 1000);
}
Clock.prototype.updateClock = function() {
var rem = this.getTimeRemaining();
// Update time element
var duration = [
rem.days,
this.padLeft(rem.hours),
this.padLeft(rem.minutes),
this.padLeft(rem.seconds)
];
this.timeEl.innerHTML = duration.join(":");
// Update progress
var progress = this.getProgress(rem.total);
this.progressEl.style.width = (progress * 100) + "%";
// Clear intervall when done
if(rem.t === 0 && this.interval) {
clearInterval(this.interval);
delete this.interval;
}
};
Clock.prototype.padLeft = function(number) {
return ('0' + number).slice(-2);
};
Clock.prototype.getTimeRemaining = function() {
var t = this.endDate - new Date();
if(t < 0) t = 0;
return {
total: t,
days: Math.floor(t / (1000 * 60 * 60 * 24)),
hours: Math.floor((t / (1000 * 60 * 60)) % 24),
minutes: Math.floor((t / 1000 / 60) % 60),
seconds: Math.floor((t / 1000) % 60)
};
};
Clock.prototype.getProgress = function(remainingTime) {
var totalTime = this.endDate - this.startDate;
return 1 - (remainingTime / totalTime);
};
// Example. Replace startDate and endDate with your dates (30sec for demo)
var startDate = new Date();
var endDate = new Date(Date.now() + 30 * 1000);
new Clock("clockdiv", startDate, endDate);
#clockdiv {
font-weight: 600;
text-transform: uppercase;
}
.progress {
margin-bottom: 8px;
border-radius: 4px;
}
.progress-bar {
width: 100%;
border-radius: 4px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="clockdiv">
<div>
Time Remaining:
<span class="time"></span>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped active"></div>
</div>
</div>
Hi i got the countdown timer code from :
https://codepen.io/SitePoint/pen/MwNPVq,
and have modified as :
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
return {
'total': t,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
if(t.minutes == 0 && t.seconds ==0) {
console.log('in this func');
deadline = new Date(deadline.getTime() + 10*60000);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
deadline = new Date(Date.parse('Fri Mar 30 2018 17:03:00 GMT+0530'));
initializeClock('clockdiv', deadline);
what change, i have done is, i have checked if minutes and seconds both are 0, then the variable 'deadline' should be updated with new time. The countdown timer works fine but as it hits 0:0, it enters the function and everything stops.
You need to initialize clock again when it hits 0:0 (updated pen)
if (t.minutes == 0 && t.seconds == 0) {
console.log('in this func');
deadline = new Date(deadline.getTime() + 10 * 60000);
initializeClock('clockdiv', deadline); //added this line
}
Demo
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
if (t.minutes == 0 && t.seconds == 0) {
console.log('in this func');
deadline = new Date(deadline.getTime() + 10 * 60000);
initializeClock('clockdiv', deadline); //added this line
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 1 * 1 * 1 * 6 * 1000);
initializeClock('clockdiv', deadline);
body {
text-align: center;
background: #00ECB9;
font-family: sans-serif;
font-weight: 100;
}
h1 {
color: #396;
font-weight: 100;
font-size: 40px;
margin: 40px 0px 20px;
}
#clockdiv {
font-family: sans-serif;
color: #fff;
display: inline-block;
font-weight: 100;
text-align: center;
font-size: 30px;
}
#clockdiv>div {
padding: 10px;
border-radius: 3px;
background: #00BF96;
display: inline-block;
}
#clockdiv div>span {
padding: 15px;
border-radius: 3px;
background: #00816A;
display: inline-block;
}
.smalltext {
padding-top: 5px;
font-size: 16px;
}
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
My countdown timer I want to put on a site is having some issues. Countdown is normal, everything is fine, but at the end of the timer, instead of it to clear the timer and display the end message or a call back, it will rather display the end message by the side while time continues to read in the negative.
Can anyone show me what went wrong?
This is my code:
// Set the date we're counting down to
var countDownDate = new Date("March 31, 2017 09:35:00 PM").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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("endmessage").innerHTML = "EXPIRED";
}
}, 1000);
body {
background: #f6f6f6;
}
.countdownContainer{
position: absolute;;
top: 50%;
left: 50%;
transform : translateX(-50%) translateY(-50%);
text-align: center;
background: #ddd;
border: 1px solid #999;
padding: 10px;
box-shadow: 0 0 5px 3px #ccc;
}
.info {
font-size: 80px;
}
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<table class="countdownContainer">
<tr class="info">
<td colspan="4">Countdown to April fool</td>
</tr>
<tr class="info">
<td id="days">00</td>
<td id="hours">00</td>
<td id="minutes">00</td>
<td id="seconds">00</td>
<td id="endmessage"></td>
</tr>
<tr>
<td>Days</td>
<td>Hours</td>
<td>Minutes</td>
<td>Seconds</td>
</tr>
</table>
<p id="demo"></p>
<script>
</script>
</body>
</html>
I have made some changes to your code. Please find it below,
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body {
background: #f6f6f6;
}
.countdownContainer{
position: absolute;;
top: 50%;
left: 50%;
transform : translateX(-50%) translateY(-50%);
text-align: center;
background: #ddd;
border: 1px solid #999;
padding: 10px;
box-shadow: 0 0 5px 3px #ccc;
}
.info {
font-size: 80px;
}
</style>
</head>
<body>
<table class="countdownContainer">
<tr class="info">
<td colspan="4">Countdown to April fool</td>
</tr>
<tr class="info">
<td id="days">00</td>
<td id="hours">00</td>
<td id="minutes">00</td>
<td id="seconds">00</td>
<td id="endmessage"></td>
</tr>
<tr>
<td>Days</td>
<td>Hours</td>
<td>Minutes</td>
<td>Seconds</td>
</tr>
</table>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 01, 2017 12:00:30 PM").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 the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("endmessage").innerHTML = "EXPIRED";
}
else{
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = seconds;
}
}, 1000);
</script>
</body>
</html>
Each time the countdown is printed, it should be done only if the difference is greater than 0. So moved that part inside the else condition of your IF. Adjust the date accordingly to test your countdown.
Is it not already the 1st of april? It is counting down to a day already passed as in the 31 of march?
Also, you do not need PM, remove PM and just have 09 or 21 etc. Not AM/PM
<script>
// Set the date we're counting down to
var countDownDate = new Date("April 1, 2017 09:35: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);
// Output the result in an element with id="demo"
document.getElementById("days").innerHTML = days;
document.getElementById("hours").innerHTML = hours;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("seconds").innerHTML = seconds;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("endmessage").innerHTML = "EXPIRED";
}
}, 1000);
</script>
This counts down to 09:35, today.