24h countdown timer with progress bar - javascript

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.

Related

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>

How to calculate remaining time in custom html5 audio player with JavaScript?

I found a good custom HTML5 audio player and successfully redesigned it for my needs. Everything about it is ok, except it didn't show "remaining" time (how much time actually left to track end).
I want to add a calculation of time left without changing the original script, Is it possible?
[
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
CodePen (original player source code)
What you want is extremely easy, You don't have to change a lot of code but just need to add just two lines.
Inside the "initProgressBar()" function just add these two lines of code
//calculate the remaining time
var rem_time=length-current_time;
jQuery(".rem-time").html(calculateCurrentValue(rem_time));
//HTML to show the remaining time(add it to the HTML)
<small style="float: left; position: relative; left: 15px;" class="rem-time"></small>
the first line is just getting the total seconds, "length" and "current_time" was already available in the code so I am just using them, nothing new.
In the second line, I am converting the remaining time to a readable format, again using an already available function "calculateCurrentValue()" and setting an HTML element with remaining time.
At last the HTML element in which the remaining time will be shown.
You can also take a look at this CodePen which I have done for a better understanding.
Adding Full code here to make sure it is available always
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
var prevcurrentime=0;
function initProgressBar() {
var player = document.getElementById('player');
var length = player.duration
var current_time = player.currentTime;
// calculate total length of value
var totalLength = calculateTotalValue(length)
jQuery(".end-time").html(totalLength);
// calculate current value time
var currentTime = calculateCurrentValue(current_time);
jQuery(".start-time").html(currentTime);
//checking if the current time is bigger than the previous or else there will be sync different between remaining and current
if(currentTime>prevcurrentime){
//calculate the remaining time
var rem_time=length-current_time;
jQuery(".rem-time").html(calculateCurrentValue(rem_time));
}
//setting the previouscurrent time to this current time
prevcurrentime=currentTime;
//progress bar calculation
var progressbar = document.getElementById('seekObj');
progressbar.value = (player.currentTime / player.duration);
progressbar.addEventListener("click", seek);
if (player.currentTime == player.duration) {
$('#play-btn').removeClass('pause');
}
function seek(evt) {
var percent = evt.offsetX / this.offsetWidth;
player.currentTime = percent * player.duration;
progressbar.value = percent / 100;
}
};
function initPlayers(num) {
// pass num in if there are multiple audio players e.g 'player' + i
for (var i = 0; i < num; i++) {
(function() {
// Variables
// ----------------------------------------------------------
// audio embed object
var playerContainer = document.getElementById('player-container'),
player = document.getElementById('player'),
isPlaying = false,
playBtn = document.getElementById('play-btn');
// Controls Listeners
// ----------------------------------------------------------
if (playBtn != null) {
playBtn.addEventListener('click', function() {
togglePlay()
});
}
// Controls & Sounds Methods
// ----------------------------------------------------------
function togglePlay() {
if (player.paused === false) {
player.pause();
isPlaying = false;
$('#play-btn').removeClass('pause');
} else {
player.play();
$('#play-btn').addClass('pause');
isPlaying = true;
}
}
}());
}
}
initPlayers(jQuery('#player-container').length);
html {
height: 100%;
display: table;
margin: auto;
}
body {
height: 100%;
display: table-cell;
vertical-align: middle;
background: yellow;
}
.audio-player {
background: white;
border: 1px solid #dfdfdf;
width: 50vw;
text-align: center;
display: flex;
flex-flow: row;
margin: 4rem 0 4rem 0;
}
.audio-player .album-image {
min-height: 100px;
width: 110px;
background-size: cover;
}
.audio-player .player-controls {
align-items: center;
justify-content: center;
margin-top: 2.5rem;
flex: 3;
}
.audio-player .player-controls progress {
width: 90%;
}
.audio-player .player-controls progress[value] {
-webkit-appearance: none;
appearance: none;
background-color: white;
color: blue;
height: 5px;
}
.audio-player .player-controls progress[value]::-webkit-progress-bar {
background-color: white;
border-radius: 2px;
border: 1px solid #dfdfdf;
color: blue;
}
.audio-player .player-controls progress::-webkit-progress-value {
background-color: blue;
}
.audio-player .player-controls p {
font-size: 1.6rem;
}
.audio-player #play-btn {
background-image: url("http://www.lukeduncan.me/images/play-button.png");
background-size: cover;
width: 75px;
height: 75px;
margin: 2rem 0 2rem 2rem;
}
.audio-player #play-btn.pause {
background-image: url("http://www.lukeduncan.me/images/pause-button.png");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="audio-player">
<div id="play-btn"></div>
<div class="audio-wrapper" id="player-container" href="javascript:;">
<audio id="player" ontimeupdate="initProgressBar()">
<source src="http://www.lukeduncan.me/oslo.mp3" type="audio/mp3">
</audio>
</div>
<div class="player-controls scrubber">
<p>Oslo <small>by</small> Holy Esque</p>
<span id="seekObjContainer">
<progress id="seekObj" value="0" max="1"></progress>
</span>
<br>
<small style="float: left; position: relative; left: 15px;" class="start-time"></small><br/>
<small style="float: left; position: relative; left: 15px;" class="rem-time"></small>
<small style="float: right; position: relative; right: 20px;" class="end-time"></small>
</div>
<div class="album-image" style="background-image: url('https://artwork-cdn.7static.com/static/img/sleeveart/00/051/614/0005161476_350.jpg')"></div>
</div>

Countdown timer not work in my HTML

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

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>

Html countdown timer not working on page reload

Hi I am facing timer countdown problem in page reload, below is my code
<html>
<head>
<script type="text/javascript">
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.now();
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);
if (t.total <= 0) {
document.getElementById("clockdiv").className = "hidden-div";
document.getElementById("timeIsNow").className = "visible-div";
clearInterval(timeinterval);
return true;
}
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);
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = '2015-12-14T20:14:00+02:00';
initializeClock('clockdiv', deadline);
</script>
<style>
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;
}
.hidden-div {
visibility: hidden;
}
.visible-div {
visibility: visible;
}
#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;
}
</style>
</head>
<body>
<h1>Countdown Clock</h1>
<div id="clockdiv" class="visible-div">
<span class="days"></span> Days
<span class="hours"></span> Hours
<span class="minutes"></span> Minutes
<span class="seconds"></span> Seconds
</div>
</body>
</html>
when I reload my page the timer is setting to it is default time and it is displaying from setting time, I have few codes which come across online but I am unable to do this, so I am seeing some help in doing it.
Thank you.
I'm assuming you want to compute the time until e set date in the future.
You have 3 issues in your code that prevent that:
1.Your html, that is accessed by your js is loaded AFTER the js. You are referencing divs that were not loaded (for example here var clock = document.getElementById(id);). This breaks your script.
2.The element referenced here does not exist: document.getElementById("timeIsNow").className = "visible-div";. This breaks your script.
3.The target date is in the past (var deadline = '2015-12-14T20:14:00+02:00';). This does not break the script, but it clears the timer (so obviously it will only tick twice).
4.In the code you posted there is no other thing preventing you to compute the time, and it will work after reload since the date is hardcoded. Any other issues regarding timezones, date refreshing etc. are not related to the posted code.
As a side note (don't take this the wrong way, I'm just trying to help and it is a personal opinion)... the code is tragic (the scope of functions, computing on client side, indent, etc.). And the method used for computing is questionable at best; I suggest a refactoring (but those are not related with the question, just some tips).
This will helpful if you want to call on every second
function worldClockZone() {
setTimeout("worldClockZone()", 1000)
}
window.onload = worldClockZone;

Categories

Resources