Here is my code for a counter (modified from www.w3schools.com code).
I'm struggling to horizontally center the output. I have tried to wrap in a DIV and then use the following techniques to center that DIV, but no success, any pointers appreciated:
Using CSS to style the outside DIV with text-align: center;
Using CSS to style the outside DIV with margin-left: auto; & margin-right:auto;
Using Javascript to set the margin property of the output horizontally align;
<!DOCTYPE HTML>
<html>
<head>
<style>
.bigger {
text-align: center;
font-size: 1.35em;
}
.counter_p {
text-align: center;
font-size: 6em;
padding: 0px 0px 0px 0px;
line-height: 1em;
}
.counter_label {
font-size: 0.2em;
line-height: 1em;
}
}
</style>
</head>
<body>
<div class="counter_p" id="counter"></div>
<script>
function pad(str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
// Set the date we're counting down to
var countDownDate = new Date("Sep 1, 2017 15:37:25").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 = pad(String(Math.floor(distance / (1000 * 60 * 60 * 24))),2);
var hours = pad(String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),2);
var minutes = pad(String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))),2);
var seconds = pad(String(Math.floor((distance % (1000 * 60)) / 1000)),2);
// My attempt at horizontally centering the output
document.getElementById('counter').style.margin = '0 auto';
// Output the result in an element with id="counter"
document.getElementById("counter").innerHTML =
"<div style='text-align:center'>"
+ "<table border='0'>"
+ "<tr>"
+ "<td>"
+ "<div>"+ days + "</div>"
+ "<div class='counter_label'>Days</div>"
+ "</td>"
+ "<td class='bigger'>|</td>"
+ "<td>"
+ "<div>" + hours + "</div>"
+ "<div class='counter_label'>Hours</div>"
+ "</td>"
+ "<td class='bigger'>|</td>"
+ "<td>"
+ "<div>" + minutes + "</div>"
+ "<div class='counter_label' >Mins</div>"
+ "</td>"
+ "<td class='bigger'>|</td>"
+ "<td>"
+ "<div>" + seconds + "</div>"
+ "<div class='counter_label'>Secs</div>"
+ "</td>"
+ "<td>"
+ "</tr>"
+ "</table>"
+"</div>";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("counter").innerHTML = "Countdown is complete";
}
}, 1000);
</script>
</body>
</html>
Creating a container div to hold the countdown text works in this case (using the CSS flexbox with justify-content set to "center") - flexbox works correctly on window resize:
<!DOCTYPE HTML>
<html>
<head>
<style>
.bigger {
text-align: center;
font-size: 1.35em;
}
.counter_p {
text-align: center;
font-size: 6em;
padding:0px 0px 0px 0px;
line-height:1em;
}
.counter_label {
font-size:0.2em;
line-height:1em;
}
.container {
display: flex;
justify-content: center;
}
}
</style>
</head>
<body>
<div class="container">
<div class="counter_p" id="counter"></div>
</div>
<script>
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
// Set the date we're counting down to
var countDownDate = new Date("Sep 1, 2017 15:37:25").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 = pad(String(Math.floor(distance / (1000 * 60 * 60 * 24))),2);
var hours = pad(String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),2);
var minutes = pad(String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))),2);
var seconds = pad(String(Math.floor((distance % (1000 * 60)) / 1000)),2);
// Output the result in an element with id="counter"
document.getElementById("counter").innerHTML = "<div style='text-align:center'><table border='0'><tr><td><div>"+ days + "</div><div class='counter_label' >Days</div></td><td class='bigger'>|</td><td><div>" + hours + "</div><div class='counter_label'>Hours</div></td><td class='bigger'>|</td><td><div>"
+ minutes + "</div><div class='counter_label' >Mins</div></td><td class='bigger'>|</td><td><div>" + seconds + "</div><div class='counter_label'>Secs</div></td><td></tr></table></div>";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("counter").innerHTML = "Countdown is complete";
}
}, 1000);
</script>
</body>
</html>
Note: CSS Flexbox is not supported in older browsers, see CSS Flexible Box Layout Module
below, are steps to find the center of a div with JS. it will be best to attach that to on window resize event. so it will move as user change window size.
//create div via js
var div = document.createElement("div");
document.body.appendChild(div);
//find widow width
var winWidth = document.documentElement.clientWidth;
//find div width
var divWidth = div.offsetWidth;
//find center position
var centerPos = (winWidth/2) - (divWidth/2)
//put div at position
div.style.marginLeft = centerPos+'px';
div {
height: 100px;
width: 100px;
background-color: red;
}
Your issue is simply the usual question of centering with css. I recommend you get familiar with this notion because it comes a lot when programming web interfaces.
This is some topic on the subject:
How do you easily horizontally center a <div> using CSS?
https://www.w3schools.com/css/css_align.asp
I also invite you to look for youtube video:
https://www.youtube.com/watch?v=hIG-fZ2042k
My solution
use a class to center (equivalent to your second idea)
.centered {
display: table;
margin: 0 auto;
}
margin: 0 auto; works only if you div as a width or display table.
function pad (str, max) {
return str.length < max ? pad("0" + str, max) : str;
}
// Set the date we're counting down to
var countDownDate = new Date("Sep 1, 2017 15:37:25").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 = pad(String(Math.floor(distance / (1000 * 60 * 60 * 24))),2);
var hours = pad(String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),2);
var minutes = pad(String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))),2);
var seconds = pad(String(Math.floor((distance % (1000 * 60)) / 1000)),2);
// My attempt at horizontally centering the output
document.getElementById('counter').style.margin = '0 auto';
// Output the result in an element with id="counter"
document.getElementById("counter").innerHTML = "<div class='centered'><table border='0'><tr><td><div>"+ days + "</div><div class='counter_label' >Days</div></td><td class='bigger'>|</td><td><div>" + hours + "</div><div class='counter_label'>Hours</div></td><td class='bigger'>|</td><td><div>"
+ minutes + "</div><div class='counter_label' >Mins</div></td><td class='bigger'>|</td><td><div>" + seconds + "</div><div class='counter_label'>Secs</div></td><td></tr></table></div>";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("counter").innerHTML = "Countdown is complete";
}
}, 1000);
#counter{
border: 3px solid red;
}
.bigger {
text-align: center;
font-size: 1.35em;
}
.counter_p {
text-align: center;
font-size: 6em;
padding:0px 0px 0px 0px;
line-height:1em;
}
.counter_label {
font-size:0.2em;
line-height:1em;
}
.centered {
border: 3px solid blue;
display: table;
margin: 0 auto;
}
<div class="counter_p" id="counter"></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'm kind of a noob to JS and I'm starting to get used to the basics but I am struggling on passing a variable from within a function that is already in a function.. to another function.
I have looked up scope and I have declared a global variable but when I console log it displays undefined. Here is my code. The project is a bar that shows how long you are into your shift at work in percentage.
I need the percentage variable to be passed out of the timed loop and into the moveLoadingBar Function so that the bar will slowly move up as the day goes on. What am I missing?
const target = 100; //percent
let percentage;
function setup() {
//Set the start point for today at 09:00:00am
let start = new Date();
start.setHours(9, 00, 00);
setInterval(timeConversion, 1000);
function timeConversion() {
//Work out the difference in miliseconds from now to the start point.
let now = new Date();
let distance = now -= start;
// Time calculations for hours, minutes and seconds
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
let miliseconds = distance;
//Percentage of day complete **** struggling to pass variable to global variable ****
percentage = (miliseconds / target) * 100
}
}
function moveLoadingBar() {
let loadingBar = document.getElementById("myBar");
let id = setInterval(frame, 1000);
function frame() {
if (percentage >= target) {
clearInterval(id);
} else {
loadingBar.style.width = percentage + "%";
}
}
}
//debugging
setup();
moveLoadingbar();
console.log(percentage);
console.log(target);
CSS
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
}
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Hello world</title>
</head>
<body>
<h1>Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
</body>
<script src="index.js"></script>
</html>
JavaScript processes code synchronously. There is only one thread of execution. The function you pass to setTimeout() won't be invoked until the JavaScript call stack is idle. So, after you call setTimeout(), the rest of your code continues to process, all the way down to your console.log() statements at the bottom, but at that point, your timer callback still hasn't run, so you see its current value (undefined) logged.
So, really the problem is that your console.log() statements are running before the asynchronous timer runs. Moving the log into the async function shows you that it's working.
const target = 100; //percent
let percentage;
function setup() {
//Set the start point for today at 09:00:00am
let start = new Date();
start.setHours(9, 00, 00);
setInterval(timeConversion, 1000);
function timeConversion() {
//Work out the difference in miliseconds from now to the start point.
let now = new Date();
let distance = now -= start;
// Time calculations for hours, minutes and seconds
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
let miliseconds = distance;
//Percentage of day complete **** struggling to pass variable to global variable ****
percentage = (miliseconds / target) * 100;
console.log('p',percentage); // <-- You have to wait until the function has run
}
}
function moveLoadingBar() {
let loadingBar = document.getElementById("myBar");
let id = setInterval(frame, 1000);
function frame() {
if (percentage >= target) {
clearInterval(id);
} else {
loadingBar.style.width = percentage + "%";
}
}
}
//debugging
setup();
moveLoadingBar();
console.log(target);
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<title>Hello world</title>
</head>
<body>
<h1>Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
</body>
<script src="index.js"></script>
</html>
moveLoadingbar is nested function inside Setup function. Which you cant access directly,and so it was throwing an error.
const target = 100; //percent
var percentage;
function setup() {
debugger;
//Set the start point for today at 09:00:00am
let start = new Date();
start.setHours(9, 00, 00);
setInterval(timeConversion, 1000);
function timeConversion() {
//Work out the difference in miliseconds from now to the start point.
let now = new Date();
let distance = now -= start;
// Time calculations for hours, minutes and seconds
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
let miliseconds = distance;
//Percentage of day complete **** struggling to pass variable to global variable ****
percentage = (miliseconds / target) * 100;
}
}
function moveLoadingBar() {
let loadingBar = document.getElementById("myBar");
let id = setInterval(frame, 1000);
function frame() {
if (percentage >= target) {
clearInterval(id);
} else {
loadingBar.style.width = percentage + "%";
}
}
}
setup();
//moveLoadingbar(); // here is problem
console.log(percentage);
console.log(target);
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Progress Bar</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
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.
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.