Countdown timer not work in my HTML - javascript

I'm trying to get a countdown timer to work on my web page, but its not working, and I can't figure out why. I don't know if its because I linked it wrong in my HTML or if its because I missed something in my code. Any help would be appreciate.
"use strict";
setInterval(function() { ... }, 1000); // 1000 milliseconds = 1 second
// Function to display current date / time on the site
setInterval(function displayTimeAndDate() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var amOrPm;
// Check if it's a.m or p.m
if (hours < 12) {
amOrPm = "a.m";
} else {
amOrPm = "p.m";
}
document.getElementById('date').innerText = date + ":" + month + ":" + year;
document.getElementById('time').innerText = hours + ":" + minutes + ":" + seconds + " " + amOrPm;
}, 1000);
setInterval(function countdown() {
// Set the desired date (American date format: Month/Day/Year) to countdown to and the current date
var endDate = new Date('07/04/2018 09:00 PM');
var currentDate = new Date();
// Get the "distance" between the dates
var distance = endDate - currentDate;
// Initialize days, hours, minutes and seconds
var oneSecond = 1000; // 1000 milliseconds = 1 second
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
// Get distance in days, hours, minutes and seconds
var days = Math.floor(distance / oneDay);
var hours = Math.floor((distance % oneDay) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / oneSecond);
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
document.getElementById('dLeft').innerText = days;
document.getElmentById('hLeft').innerText = hours;
document.getElementById('mLeft').innerText = minutes;
document.getElementById('sLeft').innerText = seconds;
}, 1000);
<!DOCTYPE html>
<html lang="en">
<head>
<!--
New Perspectives on HTML5 and CSS3, 7th Edition
Tutorial 9
Review Assignment
Tulsa's Summer Party
Author:
Date:
Filename: tny_july.html
-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tulsa's Summer Party</title>
<link href="tny_base.css" rel="stylesheet" />
<link href="tny_layout.css" rel="stylesheet" />
<script src="tny_timer.js" defer></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<header>
<nav class="horizontal">
<ul>
<li>News</li>
<li>Night Beat</li>
<li>Tulsa Times</li>
<li>Calendar</li>
<li>City Links</li>
</ul>
</nav>
<img src="tny_banner2.png" id="logoImg" alt="" />
<h1>Tulsa's<br />Summer Party</h1>
<h2 id="timeHeading">Welcome to Tulsa</h2>
<div id="currentTime"><span>11/3/2017</span><span>2:45:12 p.m.</span></div>
</header>
<article>
<section>
<h1>Countdown to the Fireworks</h1>
<div id="countdown">
<div><span id="dLeft">58</span><br />Days</div>
<div><span id="hLeft">10</span><br />Hrs</div>
<div><span id="mLeft">14</span><br />Mins</div>
<div><span id="sLeft">48</span><br />Secs</div>
</div>
<p>Celebrate the nation's birthday at <em>Tulsa's Summer
Party</em>, a daylong extravaganza in downtown
Tulsa on the 4th of July. The festivities start at 9 a.m.
with a 5K and 10K walk or race. A great event
for the whole family. Sign up as an individual or
part of a team.
</p>
<p>The <em>Farmer's
Market</em> is also back with farm-fresh produce,
meats, and dairy. There's something for every
pallet.</p>
</section>
<section>
<p>Live music starts at 11 a.m. and continues through the day
with special appearances from <em>Falstaff
Ergo</em>, <em>Crop Circles</em>, <em>Prairie Wind</em> and
<em>James Po</em>.
</p>
<p>At 9 p.m. enjoy the <em>fireworks</em> that have won awards
as the best in the Midwest, designed and presented by
<em>Wizard Works</em>. Arrive early for the best seats!
</p>
<p>After the show, dance the night away to the music of
the <em>Chromotones</em>.
</p>
<p>See you on the 4th!</p>
</section>
<nav class="vertical">
<h1>Party Links</h1>
<ul>
<li>5K and 10K Run</li>
<li>Famer's Market</li>
<li>Wizard Works</li>
<li>Falstaff Ergo</li>
<li>Crop Circles</li>
<li>James Po</li>
<li>Tulsa Fireworks</li>
<li>Prairie Wind</li>
</ul>
</nav>
</article>
<footer>
<address>
Tulsa Summer Party ·
340 Main Street, Tulsa, OK 74102 ·
(918) 555-3481
</address>
</footer>
</body>
</html>
Screenshot of my page: http://prntscr.com/isp2hu
Ive been googling and looking at possible issues and nothing has solved my problem so far.
EDIT: Added my CSS
#charset "utf-8";
#font-face {
font-family: Segment14;
src: url('segment14.woff') format('woff'),
url('segment14.ttf') format('truetype');
}
/*
New Perspectives on HTML5 and CSS3, 7th Edition
Tutorial 9
Review Assignment
Tulsa's Summer Party Layout Style Sheet
Filename: tny_layout.css
Segment14 font designed by Paul Flo Williams. Download at:
http://www.1001fonts.com/segment14-font.html#styles
*/
/* HTML and Body styles */
html {
background: linear-gradient(to bottom, rgb(120, 84, 23), rgb(51, 51, 51));
font-family: Verdana, Geneva, sans-serif;
min-height: 100%;
}
body {
margin: 0px auto;
min-width: 340px;
max-width: 1020px;
width: 100%;
min-height: 100%;
}
/* Header styles */
header img#logoImg {
display: block;
width: 100%;
}
header {
background: linear-gradient(to bottom, black 70%, rgb(185, 0, 102));
border-bottom: 1px solid rgb(0, 0, 0);
color: white;
position: relative;
width: 100%;
}
header > h1 {
position: absolute;
top: 15px;
right: 10px;
text-align: right;
font-size: 1.3em;
letter-spacing: 0.05em;
line-height: 1em;
font-family: 'Times New Roman', serif;
font-weight: normal;
color: rgba(255, 0, 192, 0.7);
}
header > h2 {
position: absolute;
top: 15px;
left: 10px;
font-size: 0.9em;
font-weight: normal;
color: rgba(255, 82, 192, 0.8);
}
/* Navigation list styles */
header nav.horizontal {
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
-webkit-flex: 0 1;
flex: 0 1;
}
body header nav ul {
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row nowrap;
flex-flow: row nowrap;
}
nav.horizontal ul li {
-webkit-flex: 1 1;
flex: 1 1;
font-size: 0.8em;
line-height: 1.5em;
height: 1.5em;
font-family: 'Trebuchet MS', Helvetica, sans-serif;
text-shadow: black 2px 1px 0px, black 4px 2px 5px;
}
nav.horizontal ul li a {
background-color: rgba(255, 255, 255, 0.2);
display: block;
color: rgba(255, 255, 255, 0.8);
text-align: center;
}
nav.horizontal ul li a:hover {
background-color: rgba(255, 88, 192, 0.5);
}
/* Time Clock Styles */
div#currentTime {
display: block;
position: absolute;
top: 35px;
left: 10px;
background-color: transparent;
border: hidden;
color: rgba(255, 82, 192, 0.8);
width: 140px;
font-size: 0.6em;
line-height: 1.1em;
font-family: 'Trebuchet MS', Helvetica, sans-serif;
font-weight: normal;
}
div#currentTime span {
display: block;
width: 100%;
}
/* Styles for the Countdown Clock */
div#countdown {
width: 100%;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row nowrap;
flex-flow: row nowrap;
margin-top: 10px;
}
div#countdown div {
display: block;
text-align: center;
width: 100%;
line-height: 1.5em;
font-size: 0.5em;
font-family: segment14, sans-serif;
color: white;
background: rgba(51, 51, 51, 0.7);
margin: 0px 1px;
padding: 5px;
color: white;
}
div#countdown div span {
font-size: 2em;
}
/* Article Styles */
article {
background: white;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-flow: row wrap;
}
article section, article nav.vertical {
-webkit-flex: 1 1 300px;
flex: 1 1 300px;
}
section h1 {
font-size: 1.2em;
text-align: center;
margin: 10px;
}
section p {
margin: 20px;
}
/*Section 1 styles */
article section:nth-of-type(1) {
background-color: rgba(255, 0, 192, 0.6);
}
/* Section 2 styles */
article section:nth-of-type(2) {
background-color: rgba(255, 0, 192, 0.5);
}
/* Vertical navigation list styles */
nav.vertical {
background-color: rgba(255, 0, 192, 0.7);
}
nav.vertical h1 {
color: rgba(255, 255, 255, 0.7);
text-shadow: rgba(192, 0, 145, 0.8) 2px 2px 5px;
font-size: 1.35em;
letter-spacing: 3px;
text-align: center;
padding: 10px;
margin: 0px 0px 15px 0px;
background-color: rgba(233, 0, 177, 0.5);
}
nav.vertical ul li {
font-size: 0.82em;
letter-spacing: 3px;
text-align: center;
}
nav.vertical ul li a {
display: block;
padding-left: 30px;
height: 32px;
line-height: 32px;
width: auto;
color: rgb(51, 51, 51);
}
nav.vertical ul li a:hover {
background-color: rgba(255, 192, 0, 0.45);
}
/* Page footer styles */
footer {
clear: left;
display: block;
}
footer address {
display: block;
font-style: normal;
text-align: center;
font-size: 0.5em;
line-height: 20px;
height: 20px;
background-color: rgb(215, 0, 152);
color: white;
}
/* =============================================
Tablet and Desktop Styles: greater than 510px
=============================================
*/
#media only screen and (min-width:511px) {
header > h1 {
font-size: 1.9em;
}
header > h2 {
font-size: 1.1em;
}
div#currentTime {
font-size: 0.9em;
line-height: 1em;
}
div#countdown {
font-size: 1.3em;
}
footer address {
font-size: 0.6em;
}
}
/* =============================================
Tablet and Desktop Styles: greater than 640px
=============================================
*/
#media only screen and (min-width:641px) {
header > h1 {
font-size: 2.4em;
}
header > h2 {
font-size: 1.3em;
}
nav.horizontal ul li {
font-size: 1em;
}
div#currentTime {
font-size: 1em;
line-height: 1.1em;
top: 40px;
}
div#countdown {
font-size: 1.5em;
}
footer address {
font-size: 0.8em;
}
}
/* =============================================
Tablet and Desktop Styles: greater than 720px
=============================================
*/
#media only screen and (min-width: 721px) {
header > h1 {
font-size: 3.3em;
}
header > h2 {
font-size: 1.5em;
}
div#currentTime {
font-size: 1.1em;
line-height: 1.2em;
top: 40px;
}
div#countdown {
font-size: 1.7em;
}
}
/* =============================================
Tablet and Desktop Styles: greater than 1020px
=============================================
*/
#media only screen and (min-width: 1021px) {
body {
margin: 40px auto;
}
}

You could do something as simple as this:
HTML:
<div id="minutes"></div>
<div id="seconds"></div>
JavaScript:
// set minutes
var mins = 5;
// calculate the seconds (don't change this! unless time progresses at a different speed for you...)
var secs = mins * 60;
function countdown() {
setTimeout('Decrement()',1000);
}
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
// if less than a minute remaining
if (seconds < 59) {
seconds.value = secs;
} else {
minutes.innerHTML = getminutes();
seconds.innerHTML = getseconds();
}
secs--;
setTimeout('Decrement()',1000);
}
}
function getminutes() {
// minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
// take mins remaining (as seconds) away from total seconds remaining
return secs-Math.round(mins *60);
}
countdown();

I replaced your functions with my own functions.
To update the countdown / current time/date every seconds, I set an interval that executes the function every second:
setInterval(function() { ... }, 1000); // 1000 milliseconds = 1 second
Your way of gettings the date's hours, minutes, etc. is
// Function to display current date / time on the site
setInterval(function displayTimeAndDate() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
var amOrPm;
// Check if it's a.m or p.m
if (hours < 12) {
amOrPm = "a.m";
} else {
amOrPm = "p.m";
}
document.getElementById('currentTime').innerText = month + "/" + date + "/" + year + " " + hours + ":" + minutes + ":" + seconds + " " + amOrPm;
}, 1000);
setInterval(function countdown() {
// Set the desired date (American date format: Month/Day/Year) to countdown to and the current date
var endDate = new Date('07/04/2018 09:00 PM');
var currentDate = new Date();
// Get the "distance" between the dates
var distance = endDate - currentDate;
// Initialize days, hours, minutes and seconds
var oneSecond = 1000; // 1000 milliseconds = 1 second
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
// Get distance in days, hours, minutes and seconds
var days = Math.floor(distance / oneDay);
var hours = Math.floor((distance % oneDay) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / oneSecond);
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
document.getElementById('countdown').innerText = days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds"
}, 1000);
<head>
<!--
New Perspectives on HTML5 and CSS3, 7th Edition
Tutorial 9
Review Assignment
Tulsa's Summer Party
Author:
Date:
Filename: tny_july.html
-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tulsa's Summer Party</title>
<link href="tny_base.css" rel="stylesheet" />
<link href="tny_layout.css" rel="stylesheet" />
<script src="tny_timer.js" defer></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<header>
<nav class="horizontal">
<ul>
<li>News</li>
<li>Night Beat</li>
<li>Tulsa Times</li>
<li>Calendar</li>
<li>City Links</li>
</ul>
</nav>
<img src="tny_banner2.png" id="logoImg" alt="" />
<h1>Tulsa's<br />Summer Party</h1>
<h2 id="timeHeading">Welcome to Tulsa</h2>
<div id="currentTime"></div>
</header>
<article>
<section>
<h1>Countdown to the Fireworks</h1>
<div id="countdown"></div>
<p>Celebrate the nation's birthday at <em>Tulsa's Summer
Party</em>, a daylong extravaganza in downtown Tulsa on the 4th of July. The festivities start at 9 a.m. with a 5K and 10K walk or race. A great event for the whole family. Sign up as an individual or part of a team.
</p>
<p>The <em>Farmer's
Market</em> is also back with farm-fresh produce, meats, and dairy. There's something for every pallet.
</p>
</section>
<section>
<p>Live music starts at 11 a.m. and continues through the day with special appearances from <em>Falstaff
Ergo</em>, <em>Crop Circles</em>, <em>Prairie Wind</em> and
<em>James Po</em>.
</p>
<p>At 9 p.m. enjoy the <em>fireworks</em> that have won awards as the best in the Midwest, designed and presented by
<em>Wizard Works</em>. Arrive early for the best seats!
</p>
<p>After the show, dance the night away to the music of the <em>Chromotones</em>.
</p>
<p>See you on the 4th!</p>
</section>
<nav class="vertical">
<h1>Party Links</h1>
<ul>
<li>5K and 10K Run</li>
<li>Famer's Market</li>
<li>Wizard Works</li>
<li>Falstaff Ergo</li>
<li>Crop Circles</li>
<li>James Po</li>
<li>Tulsa Fireworks</li>
<li>Prairie Wind</li>
</ul>
</nav>
</article>
<footer>
<address>
Tulsa Summer Party ·
340 Main Street, Tulsa, OK 74102 ·
(918) 555-3481
</address>
</footer>
</body>
Edit:
This time I didn't modify the HTML:
(I put it in a executable code snippet, otherwise I wouldn't be able to format it properly.)
// Function to display current date / time on the site
setInterval(function displayTimeAndDate() {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var amOrPm;
// Check if it's a.m or p.m
if (hours < 12) {
amOrPm = "a.m";
} else {
amOrPm = "p.m";
}
document.getElementById('date').innerText = date + ":" + month + ":" + year;
document.getElementById('time').innerText = hours + ":" + minutes + ":" + seconds + " " + amOrPm;
}, 1000);
setInterval(function countdown() {
// Set the desired date (American date format: Month/Day/Year) to countdown to and the current date
var endDate = new Date('07/04/2018 09:00 PM');
var currentDate = new Date();
// Get the "distance" between the dates
var distance = endDate - currentDate;
// Initialize days, hours, minutes and seconds
var oneSecond = 1000; // 1000 milliseconds = 1 second
var oneMinute = oneSecond * 60;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
// Get distance in days, hours, minutes and seconds
var days = Math.floor(distance / oneDay);
var hours = Math.floor((distance % oneDay) / oneHour);
var minutes = Math.floor((distance % oneHour) / oneMinute);
var seconds = Math.floor((distance % oneMinute) / oneSecond);
// Place 0 before the numbers if the are lower than 10
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
document.getElementById('dLeft').innerText = days;
document.getElmentById('hLeft').innerText = hours;
document.getElementById('mLeft').innerText = minutes;
document.getElementById('sLeft').innerText = seconds;
}, 1000);

Take a look at FlipClock.js
The html...
<html>
<head>
<link rel="stylesheet" href="/assets/css/flipclock.css">
</head>
<body>
<div class="your-clock"></div>
<script src="/assets/js/libs/jquery.js"></script>
<script src="/assets/js/flipclock/flipclock.min.js"></script>
</body>
</html>
Instantiating in JQuery...
var clock = $('.your-clock').FlipClock({
// ... your options here
});
Instantiating in JavaScript...
var clock = new FlipClock($('.your-clock'), {
// ... your options here
});

Related

im making a simple clock which have two buttons 1st for 12 hour format and 2nd for 24 hour format but button wont work when one button is working :JS

NOTE-I'm new to JS and in this code, 24 hour clock runs and when I tap on 12 hour clock format
button it won't replace with 24 hour clock format. basically the button wont work or it wont
replace the clock format plz help
I used a window. Onload function which runs the 24 hour format clock and when I tap on 12 hour format clock button it wont replace
just run the code u'll understand what I mean
the only thing I want to achieve in this code is a clock which have two button 1st:12 hour format 2nd:24 hour format,
to change clock format on a tap
window.onload = (event) => {
clock_24();
};
function clock_24() {
let a;
let date;
let time;
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
setInterval(() => {
a = new Date();
date = a.toLocaleDateString(undefined, options);
let hours = String(a.getHours()).padStart(2, '0');
let min = String(a.getMinutes()).padStart(2, '0');
let sec = String(a.getSeconds()).padStart(2, '0');
let milli = a.getMilliseconds();
time = hours + ':' + min + ':' + sec + ':' + milli;
document.getElementById('time').innerHTML = time
document.getElementById('date').innerHTML = date
}, 1);
// foramt-change
document.getElementById("format").innerHTML = "24 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('24_loaded');
}
// onclick - event-12-hour-format-clock
// time-12f
function clock_12() {
setInterval(() => {
var date = new Date();
var hh_12 = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
var session_12 = date.getHours() >= 12 ? "PM" : "AM";
hh_12 = hh_12 < 10 ? "0" + hh_12 : hh_12;
var mm_12 = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var ss_12 = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
tt_12 = hh_12 + ":" + mm_12 + ":" + ss_12 + " " + session_12;
document.getElementById('time').innerHTML = tt_12
// date-12f
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
date = date.toLocaleDateString(undefined, options);
document.getElementById('date').innerHTML = date
}, 1000);
// foramt-change
document.getElementById("format").innerHTML = "12 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('12_loaded');
}
* {
margin: 0;
padding: 0;
}
.t-d-cont {
background-color: gray;
margin: 50px;
padding: 50px;
}
#format {
border-left: 2px solid rgb(70, 166, 239);
margin-bottom: 20px;
padding-left: 20px;
font-weight: bold;
}
.redline {
border-left: 2px solid red;
width: 100%;
padding-left: 20px;
}
.time-box {
margin-bottom: 50px;
}
#time {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.date-box {
margin-bottom: 30px;
}
#date {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn-2 {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- font link -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rokkitt:wght#100&display=swap" rel="stylesheet">
</head>
<body>
<!-- time and date container -->
<div class="t-d-cont">
<div id="format">
<h1>24 Hour format</h1>
</div>
<div class="redline ">
<div class="time-box">
<h1>Current Time: <span id="time"></span></h1>
</div>
<div class="date-box">
<h1> Today's Date: <span id="date"></span></h1>
</div>
</div>
<!-- 24 hour-button -->
<div class="dropdown">
<button class="dropbtn-2" onclick="clock_24();">24-hour-format</button>
</div>
<!-- 12 hour-button -->
<div class="dropdown">
<button class="dropbtn" onclick="clock_12();">12-hour-format</button>
</div>
</div>
</body>
</div>
</html>
When you switch the clocks, you need to stop the interval timer that's displaying using the previous format. Otherwise they both keep running, and one will overwrite the other.
Use a variable outside the functions to hold the current interval timer ID, so you can stop it with clearInterval().
window.onload = (event) => {
clock_24();
};
let timer;
function clock_24() {
let a;
let date;
let time;
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
clearInterval(timer);
timer = setInterval(() => {
a = new Date();
date = a.toLocaleDateString(undefined, options);
let hours = String(a.getHours()).padStart(2, '0');
let min = String(a.getMinutes()).padStart(2, '0');
let sec = String(a.getSeconds()).padStart(2, '0');
let milli = a.getMilliseconds();
time = hours + ':' + min + ':' + sec + ':' + milli;
document.getElementById('time').innerHTML = time
document.getElementById('date').innerHTML = date
}, 1);
// foramt-change
document.getElementById("format").innerHTML = "24 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('24_loaded');
}
// onclick - event-12-hour-format-clock
// time-12f
function clock_12() {
clearInterval(timer);
timer = setInterval(() => {
var date = new Date();
var hh_12 = date.getHours() > 12 ? date.getHours() - 12 : date.getHours();
var session_12 = date.getHours() >= 12 ? "PM" : "AM";
hh_12 = hh_12 < 10 ? "0" + hh_12 : hh_12;
var mm_12 = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var ss_12 = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
tt_12 = hh_12 + ":" + mm_12 + ":" + ss_12 + " " + session_12;
document.getElementById('time').innerHTML = tt_12
// date-12f
const options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
date = date.toLocaleDateString(undefined, options);
document.getElementById('date').innerHTML = date
}, 1000);
// foramt-change
document.getElementById("format").innerHTML = "12 Hour format";
document.getElementById("format").style.fontSize = "32px";
document.getElementById("format").style.fontfamily = 'Times New Roman';
console.log('12_loaded');
}
* {
margin: 0;
padding: 0;
}
.t-d-cont {
background-color: gray;
margin: 50px;
padding: 50px;
}
#format {
border-left: 2px solid rgb(70, 166, 239);
margin-bottom: 20px;
padding-left: 20px;
font-weight: bold;
}
.redline {
border-left: 2px solid red;
width: 100%;
padding-left: 20px;
}
.time-box {
margin-bottom: 50px;
}
#time {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.date-box {
margin-bottom: 30px;
}
#date {
font-family: 'Rokkitt', serif;
font-size: 45px;
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn-2 {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
margin-left: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- font link -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rokkitt:wght#100&display=swap" rel="stylesheet">
</head>
<body>
<!-- time and date container -->
<div class="t-d-cont">
<div id="format">
<h1>24 Hour format</h1>
</div>
<div class="redline ">
<div class="time-box">
<h1>Current Time: <span id="time"></span></h1>
</div>
<div class="date-box">
<h1> Today's Date: <span id="date"></span></h1>
</div>
</div>
<!-- 24 hour-button -->
<div class="dropdown">
<button class="dropbtn-2" onclick="clock_24();">24-hour-format</button>
</div>
<!-- 12 hour-button -->
<div class="dropdown">
<button class="dropbtn" onclick="clock_12();">12-hour-format</button>
</div>
</div>
</body>
</div>
</html>

How can I make this countdown reset every week after showing a message for 1 day? code included

So I have a countdown which counts down then displays a message which works well. The thing I have to manually edit the date to restart the countdown. I want it to display the message for that day only, then once that day has ended, reset and count down again automatically.
Thank you for your help.
This is the code so far:
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 = ('0' + t.days).slice(-2);
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) {
document.getElementById("clockdiv").className = "hidden-div";
document.getElementById("timeIsNow").className = "visible-div";
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = 'April 28 2021 20:00:00 GMT+01';
//var deadline = new Date(Date.parse(new Date()) + 100 * 24 * 60 * 60 * 1000); // sets 15 day countdown
initializeClock('clockdiv', deadline);
// getTimeRemaining(deadline).minutes;
<style>
.cent {
margin: auto;
width: 50%;
padding: 10px;
text-align: center;
}
h1{
color: #396;
font-weight: 500;
font-size: 30px;
margin: 0px 0px 0px;
}
#clockdiv{
font-family: sans-serif;
color: #fff;
display: inline-block;
font-weight: 100;
text-align: center;
font-size: 20px;
}
#clockdiv > div{
padding: 10px;
border-radius: 8px;
background: #121212;
display:inline-block;
margin: 1px;
}
#clockdiv div > span{
padding: 08px;
border-radius: 8px;
background: #f12e70;;
display: inline-block;
}
.smalltext{
padding-top: 5px;
font-size: 16px;
}
.hidden-div {
visibility: hidden;
}
.visible-div {
visibility: visible;
}
</style>
<div id="timeIsNow" class="hidden-div">
<h1>Message is Live</h1>
</div>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="smalltext">D</div>
</div>
<div>
<span class="hours"></span>
<div class="smalltext">H</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">M</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">S</div>
</div>
</div>
When
t.total <= 0
Set deadline to current time at time of completion.. something like
new Date().toISOString()
From your code you have deadline set to endtime inside initializeClock(id, endtime) so you would update endtime inside the function when time is 0
endtime = new Date().toISOString()
There will no doubt still be some further changes but this would be the essence of it.

24h countdown timer with progress bar

I am working on an application to help people create new habits or discard old ones. For this application, I want to have a countdown timer which counts down every day, thanks to this post I got this to work, the next step is to add a progress bar which counts down along with the timer (so basically 00:00 = full progress bar, 23:59 = empty progress bar).
I have been looking everywhere but I can't seem to figure it out or even get a start with it. I would like to see #goal-time decreasing.
I hope someone could give me some directions/hints or even some snippets if that's possible! Thanks!
(function() {
var start = new Date;
start.setHours(24, 0, 0); //hh:mm:ss
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
.goal-progress {
border-color: black;
border-style: solid;
border-width: thick;
height: 80px;
margin-top: 50px;
margin-left: 20px;
margin-right: 20px;
background-color: black;
}
#time {
float: right;
line-height: 80px;
margin-right: 20px;
background-color: black;
color: white;
mix-blend-mode: difference;
}
.goal-time-container {
height: 80px;
background-color: white;
margin-left: 115px;
}
#goal-time {
background-color: black;
height: 80px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="goal-progress">
<div id="time"></div>
<!-- time countdown -->
<div id="img"></div>
<div class="goal-time-container">
<!-- container of the progress bar -->
<div id="goal-time"></div>
<!-- soon to (hopefully) be progress bar -->
</div>
</div>
To achieve this you can take the seconds held in the remain variable and use them to work out the percentage of the seconds remaining in one day, 86400, and then set that percentage as the width of the progress bar:
(function() {
var start = new Date;
start.setHours(24, 0, 0); //hh:mm:ss
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) { // too late, go to tomorrow
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
// bar width calulation:
var pc = remain * (100 / 86400);
document.querySelector('#goal-time').style.width = pc + '%';
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
.goal-progress {
border: 5px solid #000;
height: 80px;
margin: 50px 20px 20px 0;
background-color: black;
}
#time {
float: right;
line-height: 80px;
margin-right: 20px;
background-color: black;
color: white;
mix-blend-mode: difference;
}
.goal-time-container {
height: 80px;
background-color: white;
margin-left: 115px;
}
#goal-time {
background-color: black;
height: 80px;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="goal-progress">
<div id="time"></div>
<div id="img"></div>
<div class="goal-time-container">
<div id="goal-time"></div>
</div>
</div>
You can user getTime() function to get the number of milliseconds difference b/w two dates.
eg
let diff = new Date("<future_date>").getTime() - new Date().getTime();
You can use diff value to set the progressbar style (width or percentage or whatever).
Another solution would be to add:
const totalSeconds = 24 * 60 * 60;
right after:
start.setHours(24,0,0)
Then add:
document.getElementById('goal-time').style.width = ((remain / totalSeconds) * 100) + '%';
right after:
document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
to calculate the width of your progress bar.

How do I add vertical lines between numbers using or without using javascript?

I've created a timer to count down to a specific date, it displays with no problem. But this time, I'd like to add vertical lines separating them. I attempted to borderLeft and height to see a vertical line, but had no luck. I do see the 1px solid border, though. The picture below illustrates what I want to see in the browser.
I also want the words (days, hours, minutes, seconds) to appear underneath the numbers. Based on the picture, it appears directly next to them. I attempted to use \n because I thought it would put the word in a new line, but that didn't work.
Do we even need use javascript achieve these things? What am I doing wrong and how can I fix it?
Here's my js:
var timerDisplay = document.getElementById("timer");
timerDisplay.innerHTML = days + "\ndays " + hours + "\nhours " + minutes + "\nminutes " + seconds + "\nseconds ";
timerDisplay.style.border = "1px solid";
timerDisplay.style.borderLeft = "6px solid"
timerDisplay.style.height = "10px";
Here's my html:
<p id="timer"></p>
You could add inline elements into the p, thus you could apply some styles to achieve your objective.
For example:
const timerDisplay = document.querySelector("#timer")
timerDisplay.appendChild(createSpan('126 days'))
timerDisplay.appendChild(createSpan('5 hours'))
timerDisplay.appendChild(createSpan('16 minutes'))
timerDisplay.appendChild(createSpan('33 seconds'))
function createSpan (text) {
const span = document.createElement('span')
span.textContent = text
return span
}
And with proper styles:
p {
border: solid 5px black;
background-color: teal;
}
span {
display: inline-block;
border-right: solid 5px black;
}
p span:first-child {
text-align: right;
width: 150px;
}
span:last-child {
border-right: none;
}
On the other hand, you could change your html code:
<p id="timer">
<span class="days">126 days</span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</p>
And then, you could change the span elements directly:
const timerDisplay = document.querySelector("#timer")
const days = timerDisplay.querySelector('.days')
const hours = timerDisplay.querySelector('.hours')
const minutes = timerDisplay.querySelector('.minutes')
const seconds = timerDisplay.querySelector('.seconds')
days.textContent = '126 days'
hours.textContent = '5 hours'
minutes.textContent = '16 minutes'
seconds.textContent = '33 seconds'
And with the same styles:
p {
border: solid 5px black;
background-color: teal;
}
span {
display: inline-block;
border-right: solid 5px black;
}
p span:first-child {
text-align: right;
width: 150px;
}
span:last-child {
border-right: none;
}
You can show the example in this jsfiddle: jsfiddle example
As Temani Afif mentioned in comments, you should devide each number to separate span and style them the way you like.
Here is a working example:
function countdown(endDate) {
let days, hours, minutes, seconds;
endDate = new Date(endDate).getTime();
if (isNaN(endDate)) {
return;
}
setInterval(calculate, 1000);
function calculate() {
let startDate = new Date();
startDate = startDate.getTime();
let timeRemaining = parseInt((endDate - startDate) / 1000);
if (timeRemaining >= 0) {
days = parseInt(timeRemaining / 86400);
timeRemaining = (timeRemaining % 86400);
hours = parseInt(timeRemaining / 3600);
timeRemaining = (timeRemaining % 3600);
minutes = parseInt(timeRemaining / 60);
timeRemaining = (timeRemaining % 60);
seconds = parseInt(timeRemaining);
document.getElementById("days").innerHTML = parseInt(days, 10)+' days';
document.getElementById("hours").innerHTML = ("0" + hours).slice(-2)+' hours';
document.getElementById("minutes").innerHTML = ("0" + minutes).slice(-2)+' minutes';
document.getElementById("seconds").innerHTML = ("0" + seconds).slice(-2)+' seconds';
} else {
return;
}
}
}
(function () {
countdown('04/01/2025 05:00:00 PM');
}());
.wrapper {
background: #0084FF;
border: #000 1px solid;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
span:not(:last-child) {
border-right: #000 1px solid;
}
span {
padding: 0 5px;
white-space: nowrap;
}
<div class="wrapper">
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>
</div>

Align Title To Each Number in Javascript Countdown Timer

How do you center align each span over each Day, Hour, Min, Sec? Currently just adding padding to the text but it doesn't align to it's respective number. And when any number column goes to single digits it shifts the numbers.
Pen: https://codepen.io/zepzia/pen/MmoVJm
// Set the date we're counting down to
var countDownDate = new Date("Oct 7, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("countdown").innerHTML = days + " " + hours + " " +
minutes + " " + seconds + " ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "EXPIRED";
}
}, 1000);
body {
background: url(http://4.bp.blogspot.com/_AQ0vcRxFu0A/S9shDGGyMTI/AAAAAAAAAYk/kn3WTkY2LoQ/s1600/IMG_0714.JPG);
background-size: cover;
background-position: center center;
background-attachment: fixed;
}
.countdown-wrapper {
position: relative;
height: 400px;
}
#countdown,
#countdown-text {
font-family: 'Roboto', sans-serif;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#countdown {
font-weight: 900;
font-size: 142px;
color: #fff;
opacity: .7;
letter-spacing: -4px;
}
#countdown-text {
font-weight: 900;
font-size: 40px;
color: black;
opacity: .8;
}
.counter-text {
padding: 20px;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:400,900" rel="stylesheet">
<div class="countdown-wrapper">
<div id="countdown"></div>
<div id="countdown-text">
<span class="counter-text">DAYS</span>
<span class="counter-text">HOURS</span>
<span class="counter-text">MINS</span>
<span class="counter-text">SECS</span>
</div>
</div>
Rather than put your countdown numbers that update dynamically into a single div, create a seperate div for days, hours, minutes and seconds.
<div class="countdown-wrapper">
<div class="countdown-chunk">
<div class="counter-value" id="daysValue"></div>
<div class="counter-label">DAYS</div>
</div>
<div class="countdown-chunk">
<div class="counter-value" id="hoursValue"></div>
<div class="counter-label">HOURS</div>
</div>
<div class="countdown-chunk">
<div class="counter-value" id="minutesValue"></div>
<div class="counter-label">MINUTES</div>
</div>
<div class="countdown-chunk">
<div class="counter-value" id="secondsValue"></div>
<div class="counter-label">SECONDS</div>
</div>
</div>
Now you align each countdown-chunk with flexbox and make sure to add text-align: center to the countdown-chunk as well. You can style counter-value and counter-label independently.
.countdown-chunk {
display: flex;
flex-direction: row;
justify-content: space-around;
}
.countdown-wrapper {
flex: 1 1 50%;
text-align: center;
}
You also have 4 elements to update instead of just one, but that is easy compared to trying to align disjointed elements.
I've done something similar to TxRegex's answer. I've restructured your html, made some adjustments to your css and in your javascript I've replaced:
document.getElementById("countdown").innerHTML = days + " " + hours + " " +
minutes + " " + seconds + " ";
with:
document.getElementById("daysTicker").innerHTML = days;
document.getElementById("hoursTicker").innerHTML = hours;
document.getElementById("minsTicker").innerHTML = minutes;
document.getElementById("secsTicker").innerHTML = seconds;
to place them in the newly created divs.
Here's the updated Codepen.
Please try this
.row {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
flex-direction: row;
}
.column {
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
flex-direction: column;
}
<div class="row">
<div class="column">
<div class="counter-text" id="days"></div>
<div class="counter-text" id="hours"></div>
<div class="counter-text" id="minutes"></div>
<div class="counter-text" id="secs"></div>
</div>
<div class="column">
<div class="counter-text">DAYS</div>
<div class="counter-text">HOURS</div>
<div class="counter-text">MINUTES</div>
<div class="counter-text">SECS</div>
</div>
</div>
//javascript
document.getElementById("days").innerHTML = days ;
document.getElementById("hours").innerHTML = hours ;
document.getElementById("minutes").innerHTML = minutes ;
document.getElementById("secs").innerHTML = secs ;
You need to restructure your HTML a bit so that the number and the label are in the same containing element. This lets you put a "box" around them so that they always line up. Here's one way to do that:
// Set the date we're counting down to
var countDownDate = new Date("Oct 7, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("counter-days").innerHTML = days;
document.getElementById("counter-hours").innerHTML = hours;
document.getElementById("counter-mins").innerHTML = minutes;
document.getElementById("counter-secs").innerHTML = seconds;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "EXPIRED";
}
}, 1000);
body {
background: url(http://4.bp.blogspot.com/_AQ0vcRxFu0A/S9shDGGyMTI/AAAAAAAAAYk/kn3WTkY2LoQ/s1600/IMG_0714.JPG);
background-size: cover;
background-position: center center;
background-attachment: fixed;
}
.countdown-wrapper {
position: relative;
height: 400px;
}
#countdown {
font-family: 'Roboto', sans-serif;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#countdown > div {
float: left;
padding: 20px;
}
.counter-num {
font-weight: 900;
font-size: 142px;
color: #fff;
opacity: .7;
letter-spacing: -4px;
}
.counter-text {
display: block;
clear: both;
font-weight: 900;
font-size: 40px;
color: black;
opacity: .8;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:400,900" rel="stylesheet">
<div class="countdown-wrapper">
<div id="countdown">
<div id="countdown-days">
<span class="counter-num" id="counter-days"></span>
<span class="counter-text">DAYS</span>
</div>
<div id="countdown-hours">
<span class="counter-num" id="counter-hours"></span>
<span class="counter-text">HOURS</span>
</div>
<div id="countdown-mins">
<span class="counter-num" id="counter-mins"></span>
<span class="counter-text">MINS</span>
</div>
<div id="countdown-secs">
<span class="counter-num" id="counter-secs"></span>
<span class="counter-text">SECS</span>
</div>
</div>
</div>

Categories

Resources