CSS Animation not clearing in JS - javascript

I'm penning a digital clock and I want to create a feature that slides the numbers up on change. I'm applying inline animation to the secondDiv and clearing it every second, but the animation only shows up on page load. I want it to show every second, hence trying to clear it first. I've tried secondDiv.style.animation = "" as well as secondDiv.removeAttribute('style'), but to no avail.
Codepen Example
JS
const clock = document.querySelector("#clock-body");
const hourDiv = document.querySelector("#hours");
const minuteDiv = document.querySelector("#minutes");
const secondDiv = document.querySelector("#seconds");
const zone = document.querySelector("#zone");
const getDate = () => {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (seconds < 10) {
seconds = `0${seconds}`;
}
hourDiv.textContent = hours;
minuteDiv.textContent = minutes;
secondDiv.textContent = seconds;
secondDiv.style.animation = `0.3s change`;
};
window.setInterval(getDate, 1000);
CSS
#keyframes change {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-30px);
}
}
What am I doing wrong? How can I clear the Inline Animation every second before it's applied again?

Remove style just after animation is finished with help of animationend event. Without waiting for next loop.
Instead of:
secondDiv.removeAttribute("style");
Use
secondDiv.addEventListener('animationend', () => {
secondDiv.removeAttribute("style");
});
outside your getDate function
Full example
const clock = document.querySelector("#clock-body");
const hourDiv = document.querySelector("#hours");
const minuteDiv = document.querySelector("#minutes");
const secondDiv = document.querySelector("#seconds");
const zone = document.querySelector("#zone");
const getDate = () => {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (seconds < 10) {
seconds = `0${seconds}`;
}
hourDiv.textContent = hours;
minuteDiv.textContent = minutes;
secondDiv.textContent = seconds;
secondDiv.style.animation = `0.3s change`;
};
secondDiv.addEventListener('animationend', () => {
secondDiv.removeAttribute("style");
});
window.setInterval(getDate, 1000);
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(#444, #222);
height: 100vh;
color: #fff;
}
#clock-body {
display: flex;
align-items: center;
font-size: 2rem;
font-family: "Courier New", Courier, monospace;
padding: 2.5rem;
border: 10px solid #fff;
border-radius: 20px;
background: #000;
box-shadow: 0 8px 30px #212121;
span {
font-weight: 300;
font-size: 3rem;
}
#hours,
#minutes,
#seconds {
font-weight: 700;
font-size: 4rem;
border-radius: 3px;
}
}
#keyframes change {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-30px);
}
}
<div id="clock-body">
<div id="hours"></div>
<span>:</span>
<div id="minutes"></div>
<span>:</span>
<div id="seconds"></div>
<div id="zone"></div>
</div>

Here is my solution, Its not perfect, but it can be a good starting point.
I am using setTimeout inside the function along with transition property of css to control the position and opacity of the number
const clock = document.querySelector("#clock-body");
const hourDiv = document.querySelector("#hours");
const minuteDiv = document.querySelector("#minutes");
const secondDiv = document.querySelector("#seconds");
const zone = document.querySelector("#zone");
const getDate = () => {
// secondDiv.removeAttribute("style");
secondDiv.style.transition = `opacity 0.3s linear`;
secondDiv.style.transform = `translateY(0px)`;
secondDiv.style.opacity = `1`;
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = `0${minutes}`;
}
if (seconds < 10) {
seconds = `0${seconds}`;
}
hourDiv.textContent = hours;
minuteDiv.textContent = minutes;
secondDiv.textContent = seconds;
setTimeout(() => {
secondDiv.style.transition = `all 0.3s linear`;
secondDiv.style.transform = `translateY(-50px)`;
secondDiv.style.opacity = `0`;
}, 500);
};
window.setInterval(getDate, 1000);
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: linear-gradient(#444, #222);
height: 100vh;
color: #fff;
}
#clock-body {
display: flex;
align-items: center;
font-size: 2rem;
font-family: "Courier New", Courier, monospace;
padding: 2.5rem;
border: 10px solid #fff;
border-radius: 20px;
background: #000;
box-shadow: 0 8px 30px #212121;
}
#clock-body span {
font-weight: 300;
font-size: 3rem;
}
#clock-body #hours,
#clock-body #minutes,
#clock-body #seconds {
font-weight: 700;
font-size: 4rem;
border-radius: 3px;
}
#keyframes change {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-30px);
}
}
<div id="clock-body">
<div id="hours"></div>
<span>:</span>
<div id="minutes"></div>
<span>:</span>
<div class="s-div" id="seconds"></div>
<div id="zone"></div>
</div>

Related

Can the progress bar go according to the real time throughout the day?

I have my site under construction.
This will last 1 day, from 00:00 to 23:59.
I would like the progress bar to go according to the time throughout the day.
For example:
If the time is 06:00 the bar should show 25%
if it's 12:00 it shows 50%,
if it is 18:00 it should show 75%.
However, if it is 18:15, it should show the percentage in detail, for example 75.8%.
Is it possible for it to happen and work throughout the day? Thanks
function checkTime(){
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
var hours = document.querySelector(".hours");
var minutes = document.querySelector(".minutes");
var seconds = document.querySelector(".seconds");
if(hr < 10){
hr = "0" + hr;
}
if(min < 10){
min = "0" + min;
}
if(sec < 10){
sec = "0" + sec;
}
hours.textContent = hr + " : ";
minutes.textContent = min + " : ";
seconds.textContent = sec;
}
setInterval(checkTime, 500);
const progress = document.querySelector('.progress')
const percentage = document.querySelector('.progress span')
let per = 0;
function progressLoad(){
if(per>=35){
progress.style.width = `35%`;
percentage.innerHTML = "35%"
}else{
progress.style.width = `${per}%`;
percentage.innerHTML = `${per}%`;
}
per++
}
setInterval(progressLoad,90)
.bg {background:#08093cb3;}
.hours, .minutes, .seconds {
float: left;
font-size: 1.5em;
color: #008c8c;
}
.progress-wrapper {
width: 100%;
background: #222;
display: flex;
margin-bottom: 20px;
border-radius: 5px;
}
.progress {
width: 0%;
height: 10px;
background: green;
border-radius: 5px;
display: flex;
justify-content: flex-end;
}
.progress span {
color: white;
position: relative;
top: 13px;
left: 25px;
font-weight: 800;
}
<body class="bg">
<div class="hours"></div>
<div class="minutes"></div>
<div class="seconds"></div>
<br><br>
<div class="progress-wrapper">
<div class="progress">
<span>0%</span>
</div>
</div>
</body>
Simply calculate the percentage of day in checkTime()
pc = Math.round(((hr * 60 * 60 + min * 60 + sec) / (24 * 60 * 60)) * 1000) / 10;
let pc,
per = 0;
function checkTime() {
var today = new Date();
var t = [today.getHours(), today.getMinutes(), today.getSeconds()];
pc = Math.round(((t[0] * 60 * 60 + t[1] * 60 + t[2]) / (24 * 60 * 60)) * 1000) / 10;
document.querySelector(".time").textContent = t.map((d) => (d < 10 ? "0" + d : d)).join(" : ");
}
function progressLoad() {
document.querySelector(".progress").style.width = `${per >= pc ? pc : per}%`;
document.querySelector(".progress span").innerHTML = `${per >= pc ? pc : per}%`;
per++;
}
checkTime();
setInterval(checkTime, 500);
setInterval(progressLoad, 90);
.bg {
background: #08093cb3;
}
.time {
float: left;
font-size: 1.5em;
color: #008c8c;
}
.progress-wrapper {
width: 100%;
background: #222;
display: flex;
margin-bottom: 20px;
border-radius: 5px;
}
.progress {
width: 0%;
height: 10px;
background: green;
border-radius: 5px;
display: flex;
justify-content: flex-end;
}
.progress span {
color: white;
position: relative;
top: 13px;
left: 25px;
font-weight: 800;
}
<body class="bg">
<div class="time"></div>
<br><br>
<div class="progress-wrapper">
<div class="progress">
<span>0%</span>
</div>
</div>
</body>
Just Divide the total seconds elapsed by total seconds in a day to get the percentage...
// to calculate time elapsed
// variables defined outside the function
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
var sec = today.getSeconds();
function checkTime(){
hr = today.getHours();
min = today.getMinutes();
sec = today.getSeconds();
var hours = document.querySelector(".hours");
var minutes = document.querySelector(".minutes");
var seconds = document.querySelector(".seconds");
if(hr < 10){
hr = "0" + hr;
}
if(min < 10){
min = "0" + min;
}
if(sec < 10){
sec = "0" + sec;
}
hours.textContent = hr + " : ";
minutes.textContent = min + " : ";
seconds.textContent = sec;
}
setInterval(checkTime, 500);
const progress = document.querySelector('.progress')
const percentage = document.querySelector('.progress span')
function progressLoad(){
let timeElapsed = hr*60*60 + min*60 + sec
let per =
parseInt(timeElapsed*100/(24*60*60));
/*
if(per>=35){
progress.style.width = `35%`;
percentage.innerHTML = "35%"
}else{
progress.style.width = `${per}%`;
percentage.innerHTML = `${per}%`;
}
per++
*/
progress.style.width = `${per}%`;
percentage.innerHTML = `${per}%`;
}
setInterval(progressLoad,90)
.bg {background:#08093cb3;}
.hours, .minutes, .seconds {
float: left;
font-size: 1.5em;
color: #008c8c;
}
.progress-wrapper {
width: 100%;
background: #222;
display: flex;
margin-bottom: 20px;
border-radius: 5px;
}
.progress {
width: 0%;
height: 10px;
background: green;
border-radius: 5px;
display: flex;
justify-content: flex-end;
}
.progress span {
color: white;
position: relative;
top: 13px;
left: 25px;
font-weight: 800;
}
<body class="bg">
<div class="hours"></div>
<div class="minutes"></div>
<div class="seconds"></div>
<br><br>
<div class="progress-wrapper">
<div class="progress">
<span>0%</span>
</div>
</div>
</body>

Add 2 digit numbers on javascript live timer

Does anyone know how to add 2 digits on a JavaScript live timer, I have the following time with days, hours, minutes and seconds, the issue is that when it gets to digits like 1-9 it only shows 9 I want it to show 09 etc. On days, hours, minutes and seconds.
For example, currently the code is showing 1 at the moment, I want it to show 01 days etc.
(function () {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let event = "July 10, 2021 01:00:00",
countDown = new Date(event).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("days").innerText = Math.floor(distance / (day)),
document.getElementById("hours").innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById("minutes").innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById("seconds").innerText = Math.floor((distance % (minute)) / second);
//do something later when date is reached
if (distance < 0) {
let headline = document.getElementById("headline"),
countdown = document.getElementById("countdown"),
content = document.getElementById("content");
countdown.style.display = "none";
content.style.display = "block";
clearInterval(x);
}
//seconds
}, 0)
}());
.container {
color: black;
margin: 0 auto;
text-align: center;
font-family: "Nunito";
}
h1 {
font-weight: normal;
letter-spacing: .125rem;
text-transform: uppercase;
}
li {
display: inline-block;
font-size: 1.5em;
list-style-type: none;
padding: 1em;
}
li span {
display: block;
font-size: 4.5rem;
}
#media all and (max-width: 768px) {
h1 {
font-size: 1.5rem;
}
li {
font-size: 1.125rem;
padding: .85rem;
}
li span {
font-size: 3.375rem;
}
}
<div class="container" style="position: absolute;">
<div id="countdown">
<ul style="margin-top: -30px">
<li><span id="days"></span>days</li>
<li><span id="hours"></span>hours</li>
<li><span id="minutes"></span>mins</li>
<li><span id="seconds"></span>secs</li>
</ul>
<script src="script.js"></script>
</div>
String.prototype.padStart():
(function() {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;
let event = "July 10, 2021 01:00:00",
countDown = new Date(event).getTime(),
x = setInterval(function() {
let now = new Date().getTime(),
distance = countDown - now;
document.getElementById("days").innerText = String(Math.floor(distance / (day))).padStart(2, '0'),
document.getElementById("hours").innerText = String(Math.floor((distance % (day)) / (hour))).padStart(2, '0'),
document.getElementById("minutes").innerText = String(Math.floor((distance % (hour)) / (minute))).padStart(2, '0'),
document.getElementById("seconds").innerText = String(Math.floor((distance % (minute)) / second)).padStart(2, '0');
//do something later when date is reached
if (distance < 0) {
let headline = document.getElementById("headline"),
countdown = document.getElementById("countdown"),
content = document.getElementById("content");
countdown.style.display = "none";
content.style.display = "block";
clearInterval(x);
}
//seconds
}, 0)
}());
.container {
color: black;
margin: 0 auto;
text-align: center;
font-family: "Nunito";
}
h1 {
font-weight: normal;
letter-spacing: .125rem;
text-transform: uppercase;
}
li {
display: inline-block;
font-size: 1.5em;
list-style-type: none;
padding: 1em;
}
li span {
display: block;
font-size: 4.5rem;
}
#media all and (max-width: 768px) {
h1 {
font-size: 1.5rem;
}
li {
font-size: 1.125rem;
padding: .85rem;
}
li span {
font-size: 3.375rem;
}
}
<div class="container" style="position: absolute;">
<div id="countdown">
<ul style="margin-top: -30px">
<li><span id="days"></span>days</li>
<li><span id="hours"></span>hours</li>
<li><span id="minutes"></span>mins</li>
<li><span id="seconds"></span>secs</li>
</ul>
<script src="script.js"></script>
</div>
</div>

How to add lap functionality in stopwatch using Javascript?

I am working on a stopwatch and basically I have all done but I don't know how to add the lapping functionality. I want that as soon as the user clicks on the lap button, a new lap gets added on a "new line". However I am not able to do that here is my code:
let hours = 0;
let minutes = 0;
let seconds = 0;
let miliseconds = 0;
let displayMilisec = miliseconds;
let displaySec = seconds;
let displayMins = minutes;
let displayHours = hours;
let interval = null;
let status = "stopped";
let laps = null;
let lapNow = null;
function start() {
miliseconds++;
if (miliseconds < 10){
displayMilisec = "0" + miliseconds.toString();
}
else {
displayMilisec = miliseconds;
}
if(seconds < 10) {
displaySec = "0" + seconds.toString();
}
else {
displaySec = seconds;
}
if(minutes < 10) {
displayMins = "0" + minutes.toString();
}
else {
displayMins = minutes;
}
if(hours < 10) {
displayHours = "0" + hours.toString();
}
else {
displayHours = hours;
}
if (miliseconds / 100 === 1) {
seconds++;
miliseconds = 0;
if (seconds / 60 === 1) {
minutes++;
seconds = 0;
if (minutes / 60 === 1) {
hours++;
minutes = 0;
}
}
}
document.getElementById("timerMilisec").innerHTML = displayMilisec;
document.getElementById("timerSec").innerHTML = displaySec;
document.getElementById("timerMins").innerHTML = displayMins;
document.getElementById("timerHrs").innerHTML = displayHours;
}
function startStop() {
if (status === "stopped") {
interval = window.setInterval(start, 10);
document.getElementById('startBtn').innerHTML = "Stop";
status = "started";
}
else {
window.clearInterval(interval);
document.getElementById('startBtn').innerHTML = "Start";
status = "stopped";
}
}
function reset() {
window.clearInterval(interval);
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
document.getElementById("timerMilisec").innerHTML = "00";
document.getElementById("timerSec").innerHTML = "00";
document.getElementById("timerMins").innerHTML = "00";
document.getElementById("timerHrs").innerHTML = "00";
document.getElementById('startBtn').innerHTML = "Start";
status = "stopped";
}
function lap() {
lapNow = hours + " : " + minutes + " : " + seconds + " : " + miliseconds;
laps = document.getElementById('lapRecord').innerHTML + lapNow;
document.getElementById('lapRecord').innerHTML = laps;
}
body {
height: 100vh;
margin: 40px 0px 0px 0px;
background-color: #58e065;
display: flex;
justify-content: center;
overflow: hidden;
}
.display {
display: flex;
left: 50%;
align-items: center;
justify-content: center;
font-family: "nunito","poppins", sans-serif;
font-weight: 700;
font-size: 60px;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
}
p {
margin: 5px;
}
.buttons {
display: flex;
justify-content: center;
}
button {
cursor: pointer;
height: 30px;
width: 80px;
border: none;
outline: none;
border-radius: 4px;
background-color: #3b85ed;
font-family: "nunito","poppins", sans-serif;
font-size: 18px;
font-weight: 700;
color: white;
box-shadow: 3px 3px 0px #224f8f;
margin: 4px;
}
button:hover {
background-color: #224f8f;
}
h1 {
position: sticky;
background-color: #ff961d;
display: flex;
justify-content: center;
margin: 30px;
font-family: "nunito", "poppins", sans-serif;
font-size: 40px;
font-weight: 700;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
border-radius: 10px;
box-shadow: 3px 3px 0px rgb(179, 101, 0);
}
#header {
width: 100%;
height: 100px;
position: sticky;
}
#laps {
margin-top: 40px;
height: 400px;
scroll-behavior: smooth;
}
<div class="wrapper" id="wrapper">
<div class="display">
<p class="timerDisplay" id="timerHrs">00</p> :
<p class="timerDisplay" id="timerMins">00</p> :
<p class="timerDisplay" id="timerSec">00</p> :
<p class="timerDisplay" id="timerMilisec">00</p>
</div>
<div class="buttons">
<button type="button" id="startBtn" onclick="startStop()">Start</button>
<button type="button" id="resetBtn" onclick="reset()">Reset</button>
<button type="button" id="lapBtn">Lap</button>
</div>
<h1>Laps:</h1>
<div id="laps">
<p id="lapRecord">
</p>
</div>
</div>
I have used a very bad method to do this but yeah I will definitely improve it as soon as know how to add that lap function. I would appreciate an explanation of your code as I just a beginner to coding and I don't know much still. Thank you so much for reading my questions.
Well then, I've edited the code and implemented the lap functionality. Here's what I did.
I would advice you stop using inline html event listeners (onclick). So I replaced all the onclicks with addEventListener('click')
Selecting elements from the DOM is heavy on the performance of your document, so I assigned all the ids to a variable, because these elements were used a lot.
In the lap function, I used template stings to concatenate the time together, and wrapped them in a <div></div> tag with a class of lap in case you want to style the laps later.
I also removed curly braces ({ }) around one-line ifelse statements to reduce the number of lines in the code.
You can test it out here in the snippet. :-)
const lapBtn = document.getElementById('lapBtn');
const timerMilliSec = document.getElementById('timerMilliSec');
const timerSec = document.getElementById('timerSec');
const timerMins = document.getElementById('timerMins');
const timerHrs = document.getElementById('timerHrs');
const startBtn = document.getElementById('startBtn');
const resetBtn = document.getElementById('resetBtn');
const lapRecord = document.getElementById('lapRecord');
let hours = 0;
let minutes = 0;
let seconds = 0;
let miliseconds = 0;
let displayMilisec = miliseconds;
let displaySec = seconds;
let displayMins = minutes;
let displayHours = hours;
let interval = null;
let status = "stopped";
let lapNow = null;
function start() {
miliseconds++;
if (miliseconds < 10) displayMilisec = "0" + miliseconds.toString();
else displayMilisec = miliseconds;
if (seconds < 10) displaySec = "0" + seconds.toString();
else displaySec = seconds;
if (minutes < 10) displayMins = "0" + minutes.toString();
else displayMins = minutes;
if (hours < 10) displayHours = "0" + hours.toString();
else displayHours = hours;
if (miliseconds / 100 === 1) {
seconds++;
miliseconds = 0;
if (seconds / 60 === 1) {
minutes++;
seconds = 0;
if (minutes / 60 === 1) {
hours++;
minutes = 0;
}
}
}
timerMilisec.innerHTML = displayMilisec;
timerSec.innerHTML = displaySec;
timerMins.innerHTML = displayMins;
timerHrs.innerHTML = displayHours;
}
function startStop() {
if (status === "stopped") {
interval = setInterval(start, 10);
startBtn.innerHTML = "Stop";
status = "started";
} else {
clearInterval(interval);
startBtn.innerHTML = "Start";
status = "stopped";
}
}
function reset() {
clearInterval(interval);
miliseconds = 0;
seconds = 0;
minutes = 0;
hours = 0;
timerMilisec.innerHTML = "00";
timerSec.innerHTML = "00";
timerMins.innerHTML = "00";
timerHrs.innerHTML = "00";
startBtn.innerHTML = "Start";
lapRecord.innerHTML = '';
status = "stopped";
}
function lap() {
lapNow = `<div class="lap">${hours} : ${minutes} : ${seconds} : ${miliseconds}</div>`;
lapRecord.innerHTML += lapNow;
}
lapBtn.addEventListener('click', lap);
startBtn.addEventListener('click', startStop);
resetBtn.addEventListener('click', reset);
body {
height: 100vh;
margin: 40px 0px 0px 0px;
background-color: #58e065;
display: flex;
justify-content: center;
overflow: hidden;
}
.display {
display: flex;
left: 50%;
align-items: center;
justify-content: center;
font-family: "nunito", "poppins", sans-serif;
font-weight: 700;
font-size: 60px;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
}
p {
margin: 5px;
}
.buttons {
display: flex;
justify-content: center;
}
button {
cursor: pointer;
height: 30px;
width: 80px;
border: none;
outline: none;
border-radius: 4px;
background-color: #3b85ed;
font-family: "nunito", "poppins", sans-serif;
font-size: 18px;
font-weight: 700;
color: white;
box-shadow: 3px 3px 0px #224f8f;
margin: 4px;
}
button:hover {
background-color: #224f8f;
}
h1 {
position: sticky;
background-color: #ff961d;
display: flex;
justify-content: center;
margin: 30px;
font-family: "nunito", "poppins", sans-serif;
font-size: 40px;
font-weight: 700;
color: white;
text-shadow: 3px 3px 0px rgba(150, 150, 150, 1);
border-radius: 10px;
box-shadow: 3px 3px 0px rgb(179, 101, 0);
}
#header {
width: 100%;
height: 100px;
position: sticky;
}
#laps {
margin-top: 40px;
height: 400px;
scroll-behavior: smooth;
}
<div class="wrapper" id="wrapper">
<div class="display">
<p class="timerDisplay" id="timerHrs">00</p> :
<p class="timerDisplay" id="timerMins">00</p> :
<p class="timerDisplay" id="timerSec">00</p> :
<p class="timerDisplay" id="timerMilisec">00</p>
</div>
<div class="buttons">
<button type="button" id="startBtn">Start</button>
<button type="button" id="resetBtn">Reset</button>
<button type="button" id="lapBtn">Lap</button>
</div>
<h1>Laps:</h1>
<div id="laps">
<p id="lapRecord"></p>
</div>
</div>

How to make javascript countdown continue after refresh

I want to make javascript countdown continue after refreshing until the end even if page closed if possible without a database. I have done some searching but couldn't apply any on this code at all.
Can anyone help me with this one, please? I need to get it working without replacing the whole thing.
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
function timer(seconds) {
// clear any existing timers
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
// check if we should stop it!
if(secondsLeft < 0) {
document.getElementById('itimer').style.display = 'none'
document.getElementById('ifree').innerHTML = "done!";
document.getElementById("ifree").style.fontSize = "3.5rem";
clearInterval(interval);
clearInterval(countdown);
return;
}
// display it
displayTimeLeft(secondsLeft);
}, 1000);
document.getElementById('itimer').style.display = 'unset'
document.getElementById("ifree").style.fontSize = "15px";
}
function displayTimeLeft(seconds){
const minutes = Math.floor(seconds/60);
const remainderSeconds = seconds % 60;
const display = `${minutes}:${remainderSeconds < 10 ? '0' : '' }${remainderSeconds}`;``
document.title = display;
timerDisplay.textContent = display;
}
function displayEndTime(timestamp){
const end = new Date(timestamp);
const hour = end.getHours();
const minutes = end.getMinutes();
endTime.textContent = `... ${hour}:${minutes}`;
}
function startTimer() {
const seconds = parseInt(this.dataset.time);
timer(seconds);
}
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', function(e) {
e.preventDefault();
const mins = this.minutes.value;
console.log(mins);
timer(mins * 60);
this.reset();
});
.body{
direction: rtl;
font-family: 'Droid Arabic Kufi', sans-serif;
color: black;
}
#ifree{
font-size: 15px;
color:black;
}
html {
box-sizing: border-box;
font-size: 10px;
color: black;
}
*, *:before, *:after {
box-sizing: inherit;
}
.display__time-left {
font-weight: 100;
font-size: 5rem;
margin: 12px;
color:white;
text-shadow:4px 4px 0 rgba(0,0,0,0.05);
margin-bottom: -25px;
color: black;
}
.timer {
display:flex;
min-height: 35vh;
flex-direction:column;
direction: rtl;
}
.timer__controls {
display: flex;
}
.timer__controls > * {
flex:1;
}
.timer__controls form {
flex:1;
display:flex;
}
.timer__controls input {
flex:1;
border:0;
padding:2rem;
}
.timer__button {
background:none;
border:0;
cursor: pointer;
color:black;
font-size: 2.5vh;
text-transform: uppercase;
background:rgba(0,0,0,0.1);
border-bottom:3px solid rgba(0,0,0,0.2);
border-right:1px solid rgba(0,0,0,0.2);
padding:1rem;
font-family: 'Droid Arabic Kufi', sans-serif;
}
.timer__leave {
border:0;
cursor: pointer;
color:black;
font-size: 2.5vh;
text-transform: uppercase;
background:rgba(0,0,0,0.1);
border-bottom:3px solid rgba(0,0,0,0.2);
border-right:1px solid rgba(0,0,0,0.2);
padding:1rem;
font-family: 'Droid Arabic Kufi', sans-serif;
}
.timer__button:hover,
.timer__button:focus {
background:rgba(0,0,0,0.2);
outline:0;
}
.display {
flex:1;
display:flex;
flex-direction: column;
align-items: center;
justify-content: center;
max-height: 105px;
}
.display__end-time {
font-size: 3vh;
color:white;
font-family: 'Droid Arabic Kufi', sans-serif;
margin: 12px;
}
#media screen and (min-width: 1200px) {
timer__button {
font-size: 1px;
}
}
<body>
<div class="timer">
<div class="timer__controls">
<button data-time="1800" class="timer__button">30</button>
<button data-time="3600" class="timer__button">60</button>
<button data-time="5400" class="timer__button">90</button>
<button data-time="7200" class="timer__button">120</button>
<button data-time="14400" class="timer__button">240</button>
<button class="timer__leave" id="timer__leave">OFF</button>
<button data-time="0" class="timer__button">X</button>
</div>
<div class="display">
<h1 class="display__time-left" id="itimer"></h1>
<p class="display__end-time" id="ifree"></p>
</div>
</body>
Update the timer function
function timer(seconds) {
// clear any existing timers
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
// check if we should stop it!
if(secondsLeft < 0) {
document.getElementById('itimer').style.display = 'none'
document.getElementById('ifree').innerHTML = "متاح الآن!";
document.getElementById("ifree").style.fontSize = "3.5rem";
clearInterval(interval);
clearInterval(countdown);
localStorage.removeItem("timeLeft")
return;
}
// display it
localStorage.timeLeft=secondsLeft;
displayTimeLeft(secondsLeft);
}, 1000);
document.getElementById('itimer').style.display = 'unset'
document.getElementById("ifree").style.fontSize = "15px";
}
then add the below condition.
if(localStorage.timeLeft){
timer(localStorage.timeLeft);
}
Maybe use localStorage?
Add 3 additional functions:
function loadTimeLeft() {
return JSON.parse(localStorage.timeLeft)
}
function persistTimeLeft(timeLeft) {
localStorage.timeLeft = JSON.stringify(timeLeft)
}
function clearTimeLeft() {
localStorage.removeItem("timeLeft")
}
Then just plug it in:
window.onload = function() {
const seconds = loadTimeLeft()
if (seconds) {
timer(seconds)
}
}
function timer(seconds) {
....
countdown = setInterval(() => {
if(secondsLeft < 0) {
....
clearTimeLeft() //added at the end of if statement
return
}
displayTimeLeft(secondsLeft)
persistTimeLeft(secondsLeft) //added at the end of callback
}, 1000)
...

JavaScript Beep Sound incorrect on mobile but desktop

I creat short script want to make a beep sound every second.
It just a simple JS in HTML file.
When it run on desktop (chrome) it working (beep every sec) but when it run on mobile (both android and ios) it only beep once and gone.
Can anyone suggest a fix?
I try many method but cannot find a fix.
here is script
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
body {
font-family: Arial;
margin: 0 !important;
padding: 0 !important;
}
h1 {
margin-top: 1px;
margin-bottom: 1px;
margin-right: 1px;
margin-left: 1px;
}
input[type=text], select, textarea{
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
resize: vertical;
}
label {
padding: 15px 2px 2px 5px;
display: inline-block;
}
select.form-control{display:inline-block}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.button:hover {
background-color: #45a049;
}
table, th, td {
border: 0px;
padding:0;
margin:0;
border-collapse: collapse;
}
td {
border: 0px;
padding:1;
margin:0;
}
</style>
<script>
var bit = 18;
var flat = 1;
var cmd = [0,0,0,0,0,0,0,0,0,0,0,0,0];
var j =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t5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb//////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU="
)).play();
}
function clock () {
var h1 = document.getElementById('clockShow'),
seconds = 0, minutes = 0, hours = 0;
function add() {
seconds++;
secTime++
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
beep();
}
function timer() {
t = setTimeout(add, 1000);
}
/* Start button */
start.onclick = function () {
//init
document.getElementById("msg").innerHTML="UP";
document.getElementById("start").disabled = true;
timer();
}
/* Clear button */
clear.onclick = function() {
clearTimeout(t);
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
document.getElementById("msg").innerHTML="START";
j = 0;
secTime = 0;
document.getElementById("Next").innerHTML = "Count Down";
document.getElementById("start").disabled = false;
}
}
</script>
</head>
<body onload="clock()">
<div align="center">
<h1 id="msg" style="font-size:20vw">START</h1>
<span style="font-size:5vw" id="Next">Clock</span>
</div><br>
<div align="center">
<h1 id="clockShow" style="font-size:5vw"><time>00:00:00</time></h1>
<button id="start" class="button">Start</button>
<button id="clear" class="button">Abort</button>
</div>
</body>
</html>

Categories