Javascript date countdown with custom date - javascript

var timer;
var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
body {
background: #f5f5f5;
}
#timer {
font-family: Arial, sans-serif;
font-size: 20px;
color: #999;
letter-spacing: -1px;
}
#timer span {
font-size: 60px;
color: #333;
margin: 0 3px 0 15px;
}
#timer span:first-child {
margin-left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">
<span id="days"></span>days
<span id="hours"></span>hours
<span id="minutes"></span>minutes
<span id="seconds"></span>seconds
</div>

setDate() sets only Day of the current month in date object. You can directly provide your date string in YYYY-MM-DD format to Date() while creating new object.
var timer;
var compareDate = new Date('2020-06-02');
// compareDate.setDate(Date.parse('2020-06-02'));
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
body {
background: #f5f5f5;
}
#timer {
font-family: Arial, sans-serif;
font-size: 20px;
color: #999;
letter-spacing: -1px;
}
#timer span {
font-size: 60px;
color: #333;
margin: 0 3px 0 15px;
}
#timer span:first-child {
margin-left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">
<span id="days"></span>days
<span id="hours"></span>hours
<span id="minutes"></span>minutes
<span id="seconds"></span>seconds
</div>

Directly set new Date()
var compareDate = new Date('2020-06-02');

Change
var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));
to
var compareDate = new Date(2020, 05, 2);

Related

Countdown timer - using several times in a page

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>' ;
});

HTML/JavaScript Countdown Timer

I have a countdown timer that currently allows the user to input a time and start the countdown from there.
I would like to have the text change colour after a certain amount of time, for example:
Text to go orange at 50%, then text to red when only 25% of the input time is left.
I'm pretty out of my depth already so would be very grateful for some detailed advice, thanks!
Here is my current code:
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
window.onload = function() {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Enter Time');
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Start Countdown');
startButton.onclick = function() {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
}
html,
body {
font-family: helvetica;
color: #222;
background: #eaeaea;
margin: 0;
padding: 0;
box-sizing: border-box;
}
#container {
width: 400px;
margin: auto;
}
h1 {
font-size: 30em;
text-align: center;
margin: 40px 0;
padding: 0;
border-right: none;
border-left: none;
}
input {
display: block;
width: 80%;
border: 5px solid #E6E6E6;
background: #fff;
height: 50px;
margin-bottom: 5px;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
font-size: 19px;
text-align: center;
border-radius: 5px;
}
input[type=button] {
line-height: 30px;
font-size: 19px;
border: 2px solid #E6E6E6;
background: #f5b932;
color: #333;
font-weight: bold;
margin-top: 5px;
transition: .4s ease-in-out;
}
input[type=text]:focus {
outline: none;
}
input[type=button]:focus {
outline: none;
}
input[type=button]:hover {
background: #f5b934;
cursor: pointer;
}
.center-count {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 20vw;
}
<div id="container">
<div id="inputArea"></div>
</div>
<br>
<br>
<br>
<h1 id="time">0:00</h1>
Try this:
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//Convert remaining seconds to presentage of total seconds
precentageS = Math.floor(secondsRemaining/totalSeconds)*100
//Change color based on persentage
if(precentageS <= 50){
document.getElementById("time").style.color = "orange";
}else if(precentageS <= 25){
document.getElementById("time").style.color = "red";
}else{
document.getElementById("time").style.color = "blue";
}
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
totalSeconds = secondsRemaining;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
What I've done is added a totalSeconds variable after the secondsRemaining so I can keep track of how many seconds we started with. I then convert the secondsRemaining into a percentage of the totalSeconds And have if statements depending on the number of times you would like to change color.
Try something like this:
Extracted minutes to be able to calculate percentage on the run.
Added two condition to change color...
var secondsRemaining;
var intervalHandle;
// Total time
var minutes;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
// Change color by percentage
// Below 25% = 60 / 4 : red
if (secondsRemaining < minutes * 15) {
timeDisplay.style.color = "red";
}
// Below 50% = 60 / 2 : orange
else if (secondsRemaining < minutes * 30) {
timeDisplay.style.color = "orange";
}
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
window.onload = function() {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Enter Time');
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Start Countdown');
startButton.onclick = function() {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
}
html,
body {
font-family: helvetica;
color: #222;
background: #eaeaea;
margin: 0;
padding: 0;
box-sizing: border-box;
}
#container {
width: 400px;
margin: auto;
}
h1 {
font-size: 30em;
text-align: center;
margin: 40px 0;
padding: 0;
border-right: none;
border-left: none;
}
input {
display: block;
width: 80%;
border: 5px solid #E6E6E6;
background: #fff;
height: 50px;
margin-bottom: 5px;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
font-size: 19px;
text-align: center;
border-radius: 5px;
}
input[type=button] {
line-height: 30px;
font-size: 19px;
border: 2px solid #E6E6E6;
background: #f5b932;
color: #333;
font-weight: bold;
margin-top: 5px;
transition: .4s ease-in-out;
}
input[type=text]:focus {
outline: none;
}
input[type=button]:focus {
outline: none;
}
input[type=button]:hover {
background: #f5b934;
cursor: pointer;
}
.center-count {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 20vw;
}
<div id="container">
<div id="inputArea"></div>
</div>
<br>
<br>
<br>
<h1 id="time">0:00</h1>
I would go with a percentage approach, here's your code with that verification.
Set a new variable for initialTime asked.
var initialTime;
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
Then on each tick, check what's the actual percentage left on the counter.
var remainingPercentage = secondsRemaining*100/initialTime;
if (remainingPercentage === 75) {
timeDisplay.style.color = "orange";
}
if (remainingPercentage === 50) {
timeDisplay.style.color = "yellow";
}
if (remainingPercentage === 25) {
timeDisplay.style.color = "red";
}
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
When first setting secondsRemaining, store it in initialTime too.
secondsRemaining = initialTime = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
window.onload = function() {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Enter Time');
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Start Countdown');
startButton.onclick = function() {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
}

Count down clock resets

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>

javascript countdown timer restart after every 10 minutes

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>

Styling a countdown timer in jQuery

I have created a countdown timer in jQuery but i am not aware of how to go about styling it. I want to sytle it as per the attached image.
FIDDLE
jQuery:
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = days + "d, " + hours + "h, "
+ minutes + "m, " + seconds + "s";
}, 1000);
http://jsfiddle.net/456jn/44/
CSS:
#countdown {
font-family: trebuchet ms;
color: #2A3435;
border-width: 1px 1px 2px 1px;
border-style: solid;
border-color: #D2CFCA;
background: #eee;
padding: 2px;
display: inline-block;
}
#countdown span {
display: inline-block;
margin-left: 5px;
min-width: 40px;
text-align: center;
font-size: 10px;
font-weight: normal;
}
#countdown span:first-child {
margin-left: 0;
}
#countdown span span {
font-size: 18px;
display: block;
}
Javscript:
// set the date we're counting down to
var target_date = new Date("Aug 15, 2019").getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
var days_span = document.createElement("SPAN");
days_span.className = 'days';
countdown.appendChild(days_span);
var hours_span = document.createElement("SPAN");
hours_span.className = 'hours';
countdown.appendChild(hours_span);
var minutes_span = document.createElement("SPAN");
minutes_span.className = 'minutes';
countdown.appendChild(minutes_span);
var secs_span = document.createElement("SPAN");
secs_span.className = 'secs';
countdown.appendChild(secs_span);
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value.
days_span.innerHTML = '<span>' + days + '</span>' + 'Days';
hours_span.innerHTML = '<span>' + hours + '</span>' + 'Hours';
minutes_span.innerHTML = '<span>' + minutes + '</span>' + 'Minutes';
secs_span.innerHTML = '<span>' + seconds + '</span>' + 'Seconds';
Format your timer like this:
countdown.innerHTML = "<table><tr><td>"+days+"</td><td>"+hours+"</td><td>"+ minutes+"</td><td>"+seconds+"</td></tr>
<tr><td>days</td><td>hours</td><td>minutes</td><td>seconds</td></tr></table>";
Then style the table.

Categories