Vanilla JS Alarm Clock: Scope and Increment Questions - javascript

I have 2 issues with my alarm clock.
1)When the hour is increased or decreased to over 12, I want to switch from AM to PM. The problem is that where I call the today.getHours();, it's inside a different function. My increment button function (to increase/decrease) is outside that function and when moved inside the clock function holding today.getHours(), doesn't work, so I can't say when hours is greater than 12, switch to PM. And it seems redundant to call getHours again. Does anyone have any recommendations on how to fix this in vanilla JS? Is there a better way to do it?
2)When clicked, the minute decrease increment button gives negative values. I know this probably has a simple solution but I think I've been staring at it for too long to see it.
//Select Elements
const alarm_time = document.getElementById('alarmTime');
const set_alarm = document.getElementById('setAlarm');
const alarm_alert = document.getElementById('alarmAlert');
const hr_increase= document.getElementById('hourIncrease');
const hr_decrease = document.getElementById('hourDecrease');
const min_increase= document.getElementById('minuteIncrease');
const min_decrease = document.getElementById('minuteDecrease');
const increment = document.querySelectorAll('.increment');
//Variables
let hr;
let min;
let TOD;
let alarmHr=0;
let alarmMin=0;
let alarmTOD="AM";
let alarmActive=false;
//Alarm Sound
let sound = new Audio("https://res.cloudinary.com/saveallthethings/video/upload/v1565033348/Free%20Music%20Downloads/bensound-hey_vunrwo.mp3");
//Alarm Function
if (alarmHr== hr && parseInt(alarmMin) == min && alarmTOD == TOD){
sound.play();
card.classList.add("blinkingAlarm");
}
//Get Time
function clock(){
//Display Greeting, Time and Date
let today = new Date();
let year = today.getFullYear();
let date = today.getDate();
let hours = today.getHours();
let minutes = today.getMinutes();
//Specify Am or PM, and populate greeting
if (hours >= 17){
timeofDay = "PM";
} else if (hours >= 12 && hours < 17){
timeofDay = "PM";
} else {
timeofDay = " AM";
}
//Convert Hours to 12hr Format
if (hours>12){
hours = hours - 12;
}
else if (hours===0){
hours = 12;
}
//For single digit minutes, add a zero
if (minutes<10){
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (alarm_time.classList.contains("blinkingText")){
alarm_time.innerHTML = (alarmHr + ":" + alarmMin + alarmTOD);
}else{alarm_time.innerHTML = (hours + ":" + minutes + timeofDay);}
}//Closing Brackets for clock fnc
//Set Interval to Update Time
setInterval('clock()', 500);
//Count Clicks on Set Alarm Btn
let clickCounter = 0;
set_alarm.onclick = function() {
clickCounter += 1;
//Second Click sets the alarm, says "Alarm set to"
if((clickCounter % 2) === 0){
alarm_time.classList.remove("blinkingText");
alarmActive = true;
if (alarmHr == 0 && alarmMin == 0){
alarm_alert.innerHTML = "no alarm set";
}else{
alarm_alert.innerHTML = "alarm set for "+ alarmHr +":" + alarmMin + alarmTOD;
}
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
} else {
alarm_time.classList.add("blinkingText");
//Loop Over the Node List for increment
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.add("visibility");
hourDecrease.classList.add("visibility");
minuteIncrease.classList.add("visibility");
minuteDecrease.classList.add("visibility");
document.getElementById("hourIncrease").disabled = false;
document.getElementById("hourDecrease").disabled = false;
document.getElementById("minuteIncrease").disabled = false;
document.getElementById("minuteDecrease").disabled = false;
}
}
};
//Turn off alarm
dismiss.onclick = function() {
if(alarmActive = "true"){
alarmActive ="false"
alarmHr = 0;
alarmMin = 0;
alarmTOD = "AM";
alarm_alert.innerHTML = "no alarm set";
sound.pause();
alarm_time.classList.remove("blinkingText");
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
}
};
hr_increase.onclick = function() {
alarmHr++;
if (alarmHr > 12){
alarmHr= alarmHr - 12;
}
}
hr_decrease.onclick = function() {
alarmHr--;
if (alarmHr <= 0){
alarmHr= alarmHr + 12;
}
console.log(alarmHr);};
min_increase.onclick = function() {
alarmMin++;
if (alarmMin < 10){
alarmMin= "0" + alarmMin;
}
if(alarmMin > 59){
alarmMin= alarmMin-60 ;
}
if(alarmMin == 0){
alarmMin= "00";
}
}
min_decrease.onclick = function() {
alarmMin--;
if (alarmMin < 10){
alarmMin= "0" + minutes;
}
if (alarmMin < 0){
alarmMin= alarmMin % 60;
}
};
#import url('https://fonts.googleapis.com/css?family=Montserrat:900|Open+Sans:800|Source+Sans+Pro:300');
html, body {
height: 100%;
font-family: 'Source Sans Pro', sans-serif;
font-size:15px;
}
.card_container{
height:100vh;
}
.center{
display:flex;
justify-content:center;
align-items:center;
}
.card{
border-radius:15px;
background-color: rgba(254, 253, 253,0.8);
box-shadow: 0px 0px 51px -3px rgba(0,0,0,0.13);
max-width:22rem;
border:solid rgba(254, 253, 253,0.8) 0.1px;
}
.blinkingAlarm{
animation:blinkingAlarm 1.2s ease-in-out infinite;
}
#keyframes blinkingAlarm{
50%{
border:solid white 7px;}
}
.card_inner{
border-radius:15px;
margin:.75rem;
}
.card_currentContainer{
border-radius:15px;
margin-bottom:1rem;
}
.card_alarmContainer {
color:#7E7E7E;
background:#fff;
text-align:center;
}
.card_alarmContainer{
flex-direction:column;
border-radius:15px;
}
.alarmOptions{
display:flex;
color:#7E7E7E;
padding-top:.5rem;
padding-bottom:.5rem;
}
.blinkingText{
animation:blinkingText 1.6s linear infinite;
}
#keyframes blinkingText{
50%{opacity:0.3;}
}
.setBox{
flex-direction:column;
padding-left:.5rem;
padding-right:.5rem;
padding-top:0;
}
.button {
display:block;
border-style:none;
margin: 0px 0px;
padding:0px;
}
.increment{
font-size:1rem;
border:none;
background: rgba(254, 253, 253,0.8);
color:#7E7E7E;
font-family: 'Source Sans Pro', sans-serif;
cursor: pointer;
visibility:hidden;
}
.increment:hover{
cursor:pointer;
color:black;
border-style:none;
}
.visibility{
visibility:visible;
}
.alarmBox{
padding-bottom:.2rem;
}
.alarmTime{
font-size:2rem;
line-height:1rem;
padding-top:.7rem;
}
.alarmAlert{
font-size:.8rem;
text-transform:uppercase;
padding-top:.5rem;
}
.card_buttonsContainer{
width:100%;
margin:1rem 0rem;
justify-content:space-between;
flex-wrap:wrap;
}
.btn{
height:3rem;
width:8rem;
}
#setAlarm{
transition: .2s;
color:#fff;
cursor:pointer;
border-radius:15px;
background: linear-gradient(to left, #ff7e5f , #feb47b);
padding-right:.5rem;
padding-left:.5rem;
font-size:1.5rem;
margin-right:0.3rem;
}
#setAlarm:hover{
border-radius:20px;
opacity: .8;
}
#dismiss{
transition: .2s;
font-size:1.5rem;
color:#fff;
border-radius:15px;
cursor:pointer;
background: linear-gradient(to left, #64B1F2 , #00DBF3);
padding-right:.5rem;
padding-left:.5rem;
margin-left:0.3rem;
}
#dismiss:hover{
border-radius:20px;
opacity: .8;
}
/***Media Queries****/
#media only screen and (max-width:332px) {
.current_greetings{
text-align:center;
}
.card_buttonsContainer{
justify-content:center;
}
.btn{
margin-bottom:.5rem;
}
}
<div class="card_container center">
<div class ="card">
<div class="card_inner">
<div class="card_alarmContainer center">
<div class="alarmOptions ">
<div class="setBox center">
<button class="increment center" id="hourIncrease" disabled>+</button>
<button class="increment center" id="hourDecrease" disabled>−</button>
</div>
<div class="alarmBox">
<div class="alarmTime center" id="alarmTime"></div>
<div class="alarmAlert" id="alarmAlert">no alarm set</div>
</div>
<div class="setBox center">
<button class="increment center" id="minuteIncrease" disabled>+</button>
<button class="increment center" id="minuteDecrease" disabled>−</button>
</div>
</div>
</div>
<div class="card_buttonsContainer center">
<div class ="buttonBox center">
<div class="btn center" id="setAlarm">Set Alarm</div>
</div>
<div class ="buttonBox center">
<div class="btn center" id="dismiss">Dismiss</div>
</div>
</div>
</div>
</div>
</div>

In your code you need to increase and decrease the hour on the minute change. I also suggest pulling the hour increase and hour decrease out into functions (I have sample code of a working solution) so you can use them in the minute increase and decrease functions to increase or decrease the time. I also suggest using a function for the alarm time of day change so you can use it in both your hour increase and hour decrease functions. Your initial value for alarm hour was 0 but there is no 0 hour. I suggest starting with 12 for the alarm hour. I updated all of this in my sample code
The way you can update the TOD is in the hour increase check if the new hour is 12 and then toggle the TOD. In the decrease you check if the new hour is 11 and then toggle the TOD. See my sample working code!
//Select Elements
const alarm_time = document.getElementById('alarmTime');
const set_alarm = document.getElementById('setAlarm');
const alarm_alert = document.getElementById('alarmAlert');
const hr_increase= document.getElementById('hourIncrease');
const hr_decrease = document.getElementById('hourDecrease');
const min_increase= document.getElementById('minuteIncrease');
const min_decrease = document.getElementById('minuteDecrease');
const increment = document.querySelectorAll('.increment');
//Variables
let hr;
let min;
let TOD;
let alarmHr=12;
let alarmMin=0;
let alarmTOD="AM";
let alarmActive=false;
//Alarm Sound
let sound = new Audio("https://res.cloudinary.com/saveallthethings/video/upload/v1565033348/Free%20Music%20Downloads/bensound-hey_vunrwo.mp3");
//Alarm Function
if (alarmHr== hr && parseInt(alarmMin) == min && alarmTOD == TOD){
sound.play();
card.classList.add("blinkingAlarm");
}
function toggleAlarmTOD() {
if(alarmTOD === "AM") {
alarmTOD = "PM"
} else {
alarmTOD = "AM"
}
}
function increaseHr() {
alarmHr++;
if(alarmHr === 12) {
toggleAlarmTOD();
} else if (alarmHr > 12){
alarmHr = alarmHr - 12;
}
}
function decreaseHr() {
alarmHr--;
if(alarmHr <= 0) {
alarmHr = alarmHr + 12;
} else if(alarmHr === 11) {
toggleAlarmTOD();
}
}
//Get Time
function clock(){
//Display Greeting, Time and Date
let today = new Date();
let year = today.getFullYear();
let date = today.getDate();
let hours = today.getHours();
let minutes = today.getMinutes();
//Specify Am or PM, and populate greeting
if(hours >= 12){
timeofDay = "PM";
} else {
timeofDay = " AM";
}
//Convert Hours to 12hr Format
if (hours>12){
hours = hours - 12;
}
else if (hours===0){
hours = 12;
}
//For single digit minutes, add a zero
if (minutes < 10) {
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (alarm_time.classList.contains("blinkingText")){
alarm_time.innerHTML = (alarmHr + ":" + (alarmMin < 10 ? "0" + alarmMin : alarmMin) + alarmTOD);
}else{alarm_time.innerHTML = (hours + ":" + minutes + timeofDay);}
}//Closing Brackets for clock fnc
//Set Interval to Update Time
setInterval('clock()', 500);
//Count Clicks on Set Alarm Btn
let clickCounter = 0;
set_alarm.onclick = function() {
clickCounter++;
//Second Click sets the alarm, says "Alarm set to"
if((clickCounter % 2) === 0){
alarm_time.classList.remove("blinkingText");
alarmActive = true;
if (alarmHr == 0 && alarmMin == 0){
alarm_alert.innerHTML = "no alarm set";
}else{
alarm_alert.innerHTML = "alarm set for " + alarmHr + ":" + (alarmMin < 10 ? "0" + alarmMin : alarmMin) + alarmTOD;
}
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
} else {
alarm_time.classList.add("blinkingText");
//Loop Over the Node List for increment
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.add("visibility");
hourDecrease.classList.add("visibility");
minuteIncrease.classList.add("visibility");
minuteDecrease.classList.add("visibility");
document.getElementById("hourIncrease").disabled = false;
document.getElementById("hourDecrease").disabled = false;
document.getElementById("minuteIncrease").disabled = false;
document.getElementById("minuteDecrease").disabled = false;
}
}
};
//Turn off alarm
dismiss.onclick = function() {
if(alarmActive = "true") {
alarmActive ="false"
alarmHr = 12;
alarmMin = 0;
alarmTOD = "AM";
alarm_alert.innerHTML = "no alarm set";
sound.pause();
alarm_time.classList.remove("blinkingText");
//Loop that disables and hides buttons
for (var i = 0; i < increment.length; i++) {
hourIncrease.classList.remove("visibility");
hourDecrease.classList.remove("visibility");
minuteIncrease.classList.remove("visibility");
minuteDecrease.classList.remove("visibility");
document.getElementById("hourIncrease").disabled = true;
document.getElementById("hourDecrease").disabled = true;
document.getElementById("minuteIncrease").disabled = true;
document.getElementById("minuteDecrease").disabled = true;
}
}
};
hr_increase.onclick = function() {
increaseHr();
}
hr_decrease.onclick = function() {
decreaseHr();
};
min_increase.onclick = function() {
alarmMin++;
if(alarmMin > 59){
alarmMin = 0;
increaseHr();
}
}
min_decrease.onclick = function() {
alarmMin--;
if (alarmMin < 0){
alarmMin = 59;
decreaseHr();
}
};
#import url('https://fonts.googleapis.com/css?family=Montserrat:900|Open+Sans:800|Source+Sans+Pro:300');
html, body {
height: 100%;
font-family: 'Source Sans Pro', sans-serif;
font-size:15px;
}
.card_container{
height:100vh;
}
.center{
display:flex;
justify-content:center;
align-items:center;
}
.card{
border-radius:15px;
background-color: rgba(254, 253, 253,0.8);
box-shadow: 0px 0px 51px -3px rgba(0,0,0,0.13);
max-width:22rem;
border:solid rgba(254, 253, 253,0.8) 0.1px;
}
.blinkingAlarm{
animation:blinkingAlarm 1.2s ease-in-out infinite;
}
#keyframes blinkingAlarm{
50%{
border:solid white 7px;}
}
.card_inner{
border-radius:15px;
margin:.75rem;
}
.card_currentContainer{
border-radius:15px;
margin-bottom:1rem;
}
.card_alarmContainer {
color:#7E7E7E;
background:#fff;
text-align:center;
}
.card_alarmContainer{
flex-direction:column;
border-radius:15px;
}
.alarmOptions{
display:flex;
color:#7E7E7E;
padding-top:.5rem;
padding-bottom:.5rem;
}
.blinkingText{
animation:blinkingText 1.6s linear infinite;
}
#keyframes blinkingText{
50%{opacity:0.3;}
}
.setBox{
flex-direction:column;
padding-left:.5rem;
padding-right:.5rem;
padding-top:0;
}
.button {
display:block;
border-style:none;
margin: 0px 0px;
padding:0px;
}
.increment{
font-size:1rem;
border:none;
background: rgba(254, 253, 253,0.8);
color:#7E7E7E;
font-family: 'Source Sans Pro', sans-serif;
cursor: pointer;
visibility:hidden;
}
.increment:hover{
cursor:pointer;
color:black;
border-style:none;
}
.visibility{
visibility:visible;
}
.alarmBox{
padding-bottom:.2rem;
}
.alarmTime{
font-size:2rem;
line-height:1rem;
padding-top:.7rem;
}
.alarmAlert{
font-size:.8rem;
text-transform:uppercase;
padding-top:.5rem;
}
.card_buttonsContainer{
width:100%;
margin:1rem 0rem;
justify-content:space-between;
flex-wrap:wrap;
}
.btn{
height:3rem;
width:8rem;
}
#setAlarm{
transition: .2s;
color:#fff;
cursor:pointer;
border-radius:15px;
background: linear-gradient(to left, #ff7e5f , #feb47b);
padding-right:.5rem;
padding-left:.5rem;
font-size:1.5rem;
margin-right:0.3rem;
}
#setAlarm:hover{
border-radius:20px;
opacity: .8;
}
#dismiss{
transition: .2s;
font-size:1.5rem;
color:#fff;
border-radius:15px;
cursor:pointer;
background: linear-gradient(to left, #64B1F2 , #00DBF3);
padding-right:.5rem;
padding-left:.5rem;
margin-left:0.3rem;
}
#dismiss:hover{
border-radius:20px;
opacity: .8;
}
/***Media Queries****/
#media only screen and (max-width:332px) {
.current_greetings{
text-align:center;
}
.card_buttonsContainer{
justify-content:center;
}
.btn{
margin-bottom:.5rem;
}
}
<div class="card_container center">
<div class ="card">
<div class="card_inner">
<div class="card_alarmContainer center">
<div class="alarmOptions ">
<div class="setBox center">
<button class="increment center" id="hourIncrease" disabled>+</button>
<button class="increment center" id="hourDecrease" disabled>−</button>
</div>
<div class="alarmBox">
<div class="alarmTime center" id="alarmTime"></div>
<div class="alarmAlert" id="alarmAlert">no alarm set</div>
</div>
<div class="setBox center">
<button class="increment center" id="minuteIncrease" disabled>+</button>
<button class="increment center" id="minuteDecrease" disabled>−</button>
</div>
</div>
</div>
<div class="card_buttonsContainer center">
<div class ="buttonBox center">
<div class="btn center" id="setAlarm">Set Alarm</div>
</div>
<div class ="buttonBox center">
<div class="btn center" id="dismiss">Dismiss</div>
</div>
</div>
</div>
</div>
</div>

Related

Can someone tell me why my js timer isnt working?

I really dont know what is happening
I recently made this flask application and came across this error where my buttons don't works for other html table rows that are there and i don't know why. I tried my best to solve it but sadly couldn't. If someone can help me i would really appreciate it
HERE IS THE HTML CODE
<html lang="en">
<head>
<title>Timer</title>
<style>
body{
background-color: khaki;
}
h1{
font-family: monospace;
font-size:5em;
transform: translate(500px, 10px);
}
/*
h4{
font-family:monospace;
font-size: 2em;
transform: translate(700px, 10px);
} */
div.container input[type=submit] {
background-color:khaki;
border-radius: 1.8em 1.8em 1.8em;
text-transform: uppercase;
color: black;
border: none;
font-size: 2em;
font-family: monospace;
transform: translate(500px, 10px);
}
div.container input[type=text]{
transform: translate(500px, 10px);
}
table th{
text-align: left;
padding: 4px 8px;
transform: translate(500px, 10px);
}
table td{
/* background-color: aqua; */
border: 2px solid black;
padding: 4px 8px;
transform: translate(500px, 10px);
}
.btn{
background-size: 1em;
height: 2em;
width: 3em;
}
body{
margin: 0;
}
.draggable{
padding:1rem;
background-color: aliceblue;
border: 1px solid brown;
cursor: move;
}
.draggable.dragging{
opacity:0.5;
}
button.buttonReset{
color: black;
transform: scale3d(0.2, 0.2, 0.2);
}
.display{
font-family: monospace;
}
button.buttonPlay{
transform: translate(10px);
}
</style>
<link rel="shortcut-icon" href="{{url_for('static', filename='favicon.ico')}}">
</head>
<body>
<div class="container">
<h1>Task Manager</h1>
<br/>
<form action="/my_timers" method="POST">
<input type="text" placeholder="Enter New Task" name = "name" maxlength="10">
<input type="submit" value="+" class="btn btn-secondary" name="hello">
</form>
<br/><br/>
<table>
<tr>
<th>TASK</th>
<th> </th>
<th> </th>
<th>DONE</th>
<th>TIME TAKEN</th>
</tr>
</table>
{% for friend in friends%}
<table>
<tr>
<td>
<div class="container2">
<p class="draggable" draggable="true">
{{ friend.name }} Update
</p>
</div>
</td>
</p>
</td>
<td>
<a href="/delete/{{ friend.id }}">
<button class="btn"> <img src="static/7bdd1bc7db7fd48025d4e39a0e2f0fd8.jpg" alt="button" width="20" height="20" ></button>
</a>
<a href="/description">
<button class="desbtn">+<button>
</a>
</td>
<td>
<div class="stopwatch">
<div class="circle">
<span class="time" id="display">00:00:00</span>
</div>
<div class="controls">
<img id="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg" />
<img id="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg" />
<img id="resetButton" src="/static/download.png" />
</div>
</div>
</td>
</tr>
</table>
<script src="static/new.js"></script>
<!-- <table>
<td>
{{ friend.name }}
</td>
</table> -->
{% endfor%}
</div>
</body>
</html>
AND HERE IS THE JS:
const timer = document.getElementById('circle');
var hr = 0;
var min = 0;
var sec = 0;
var stoptime = true;
function startTimer() {
if (stoptime == true) {
stoptime = false;
timerCycle();
}
}
function stopTimer() {
if (stoptime == false) {
stoptime = true;
}
}
function timerCycle() {
if (stoptime == false) {
sec = parseInt(sec);
min = parseInt(min);
hr = parseInt(hr);
sec = sec + 1;
if (sec == 60) {
min = min + 1;
sec = 0;
}
if (min == 60) {
hr = hr + 1;
min = 0;
sec = 0;
}
if (sec < 10 || sec == 0) {
sec = '0' + sec;
}
if (min < 10 || min == 0) {
min = '0' + min;
}
if (hr < 10 || hr == 0) {
hr = '0' + hr;
}
timer.innerHTML = hr + ':' + min + ':' + sec;
setTimeout("timerCycle()", 1000);
}
}
function resetTimer() {
timer.innerHTML = '00:00:00';
}
The play button, pause button, reset button dont works for any other task that i add.
Please check
So you do not keep track which timer you wanter to play.
I introduce you to classes.
I tried to keep most of your original code intact but I had to made some changes.
First change is as I said, using classes.
this code created a Timer object for each .timer element so it will be easier to keep track of each individual timer.
Second change is adding event listeners so clicking on buttons actually do something
Next is removing sec = parseInt(sec);. That is unnecessary beacause you dont have to keep track of leading 0 in this variable. You can add it just before displaying it for example in printTimer() method.
class Timer
{
timer = null;
hr = 0;
min = 0;
sec = 0;
stopTime = true;
constructor(timer) {
this.timer = timer;
this.setListeners();
}
setListeners = () => {
this.timer.querySelector('.playButton').addEventListener('click', this.startTimer);
this.timer.querySelector('.pauseButton').addEventListener('click', this.stopTimer);
this.timer.querySelector('.resetButton').addEventListener('click', () => {
this.stopTimer();
this.resetTimer();
});
}
startTimer = () => {
if (this.stopTime === true) {
this.stopTime = false;
this.timerCycle();
}
}
stopTimer = () => {
if (this.stopTime === false) {
this.stopTime = true;
}
}
resetTimer = () => {
this.hr = 0;
this.min = 0;
this.sec = 0;
this.printTimer();
}
timerCycle = () => {
if (this.stopTime === false) {
this.sec += 1;
if (this.sec === 60) {
this.min += 1;
this.sec = 0;
}
if (this.min === 60) {
this.hr += 1;
this.min = 0;
}
this.printTimer();
setTimeout(this.timerCycle, 1000);
}
}
printTimer = () => {
const displayHr = this.hr < 10 ? '0' + this.hr : this.hr;
const displayMin = this.min < 10 ? '0' + this.min : this.min;
const displaySec = this.sec < 10 ? '0' + this.sec : this.sec;
this.timer.querySelector('.display').innerHTML = displayHr + ':' + displayMin + ':' + displaySec;
}
}
const timers = document.querySelectorAll('.timer');
timers.forEach(timer => {
new Timer(timer);
});
body {
background-color: khaki;
margin: 0;
}
button.buttonReset {
color: black;
transform: scale3d(0.2, 0.2, 0.2);
}
button.buttonPlay {
transform: translate(10px);
}
.display {
font-family: monospace;
}
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>
<div class="timer">
<div class="circle">
<span class="time display">00:00:00</span>
</div>
<div class="controls">
<img class="playButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/play-button_opkxmt.svg"/>
<img class="pauseButton" src="https://res.cloudinary.com/https-tinloof-com/image/upload/v1593360448/blog/time-in-js/pause-button_pinhpy.svg"/>
<img class="resetButton" src="/static/download.png"/>
</div>
</div>

How to make a count down reset

I'm trying to make a count down so that every 20 sec an alert pops up. I want it to go from 20 to 0 to 20 over and over. I have it working, but it only works once. The rage function dosen't need to be changed, it's the msg function i'm having trouble with. Here's my code.
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
var temps;
function msg() {
var idTemps = document.getElementById("temps");
temps = parseInt(idTemps.innerHTML);
temps = temps - 1;
idTemps.innerHTML = temps;
if (--temps <= 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(temps);
msg();
idTemps = 20;
var decompteur = setInterval(msg, 1000);
}
}
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button
class="bouton boutonOui"
id="boutonOui"
onclick="window.location.href='jeu_educatifs2.html'"
>
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
the first problem here is that you don't use correctly the method clearInterval. It takes as argument the id of the "timer" created with setInterval. setInterval return directly the id so actually stored it in your variable decompteur and you should use something like that to clear the timer : clearInterval(decompteur).
Also be sure to reset the idTemps with idTemps.innerHTML = 20. Then I don't really understand... Why would you clear the interval then rebuild the same again when you can just set the idTemps.innerHTML so your interval will use the 20 for temps at the next iteration ?
PS: ça fait plaisir de voir un peu de français sur stack :)
You should rewrite your code this way :
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
function msg() {
var idTemps = document.getElementById("temps");
var temps = parseInt(idTemps.innerHTML) - 1;
idTemps.innerHTML = temps;
if (--temps == 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
idTemps.innerHTML = "20";
}
}
// when you need to, stop decompteur with :
// clearInterval(decompteur);
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button class="bouton boutonOui" id="boutonOui" onclick="window.location.href='jeu_educatifs2.html'">
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
This keep as much of your code as possible, but as Rojo said, your code is very inefficent and there are a lot of things to improve.
Currently, your code is very inefficient. Rather than having your variable temps read from the DOM, you should have the variable update itself:
var temps = 20;
function msg() {
--temps;
}
setInterval(msg, 1000);
Second, you shouldn't be including var inside of that if statement:
if (countdown === 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(decompteur);
// msg(); // You don't need this
temps = 20;
decompteur = setInterval(msg, 1000); // I removed the var
}
Also, you had your variables mixed up (which I fixed)
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
var temps = 20;
var idTemps = document.getElementById("temps"); // I also moved this outside
function msg() {
--temps;
idTemps.innerHTML = temps;
if (temps === 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(decompteur);
//msg(); //You don't need this
temps = 20;
decompteur = setInterval(msg, 1000);
}
}
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button
class="bouton boutonOui"
id="boutonOui"
onclick="window.location.href='jeu_educatifs2.html'"
>
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
The following code prints the counter value each second and every 20 seconds it prints ALERT. Try to use a similar code for your example because your code is not very clear.
let counter = 0;
setInterval(() => {
counter++;
if (counter % 20 == 0) {
console.log("ALERT! ");
}
console.log("Counter Value: " + (counter % 20));
}, 1000);

How can i change it to show user to input in minutes?

I have tried to change the user input in minutes but unfortunately when I tried doing that nothing changed.
What I did was instead of "remseconds" i changed it to remminuts and changed the math as well to "x 60" but nothing happened.
const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const secInput = document.getElementById('seconds');
var seconds;
var remseconds;
var minuts;
var toCount = false;
function toSubmit() {
display('start');
remove('seconds');
remove('ok');
seconds = Number(secInput.value);
counting();
}
function display(e) {
document.getElementById(e).style.display = 'block';
}
function remove(e) {
document.getElementById(e).style.display = 'none';
}
function check(stat) {
if (stat.id == "start") {
display("stop");
remove("start");
toCount = true;
} else if (stat.id == "stop") {
display("continue");
remove("stop");
toCount = false
} else {
display("stop");
remove("continue");
toCount = true;
}
}
function count() {
if (seconds > 0) {
if (toCount == true) {
seconds--;
remseconds = seconds % 60;
minuts = Math.floor(seconds / 60);
if (minuts < 10) {
minuts = "0" + minuts;
}
if (remseconds < 10) {
remseconds = "0" + remseconds;
}
container.innerHTML = minuts + " : " + remseconds;
}
} else {
container.innerHTML = "DONE!";
buttonsDiv.style.opacity = "0";
}
}
function counting() {
remseconds = seconds % 60;
minuts = Math.floor(seconds / 60);
if (remseconds < 10) {
remseconds = "0" + remseconds;
}
container.innerHTML = minuts + " : " + remseconds;
setInterval(count, 1000);
}
<!DOCTYPE html>
<html class="class2">
<head>
<title>CountDown</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
<header>
<h1>CountDown</h1>
</header>
<div class="content">
<div class="counter"></div>
<input type="number" id="seconds" placeholder="Seconds">
<div class="buttons">
<button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
<button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
<button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
<button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
If you have any solutions please let me know.
I edited the answer here for minutes: js seconds countdown
Get minutes and only convert it to seconds by x60 in counting()
const container = document.querySelector('.counter');
const buttonsDiv = document.querySelector('.buttons');
const minInput = document.getElementById('minutes');
var seconds;
var remseconds;
var minuts;
var toCount = false;
function toSubmit() {
display('start');
remove('minutes');
remove('ok');
minuts= Number(minInput.value);
counting();
}
function display(e) {
document.getElementById(e).style.display = 'block';
}
function remove(e) {
document.getElementById(e).style.display = 'none';
}
function check(stat) {
if (stat.id == "start") {
display("stop");
remove("start");
toCount = true;
} else if (stat.id == "stop") {
display("continue");
remove("stop");
toCount = false
} else {
display("stop");
remove("continue");
toCount = true;
}
}
function count() {
if (seconds > 0) {
if (toCount == true) {
seconds--;
remseconds = seconds % 60;
minuts = Math.floor(seconds / 60);
if (minuts < 10) {
minuts = "0" + minuts;
}
if (remseconds < 10) {
remseconds = "0" + remseconds;
}
container.innerHTML = minuts + " : " + remseconds;
}
} else {
container.innerHTML = "DONE!";
buttonsDiv.style.opacity = "0";
}
}
function counting() {
seconds = minuts*60;
remseconds = seconds % 60;
//minuts = Math.floor(seconds / 60);
if (remseconds < 10) {
remseconds = "0" + remseconds;
}
container.innerHTML = minuts + " : " + remseconds;
setInterval(count, 1000);
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
html, body{
height: 100%;
}
body{
width: 100%;
height: 100%;
background: linear-gradient(to left top, #0045D6, #00A9f6);
}
header{
width: 100%;
height: 13vh;
background-color: #fff;
color: #0045F6;
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 100%;
height: 60vh;
font-size: 3rem;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.content #minutes{
width: 250px;
font-size: 2rem;
padding: 1rem;
outline: none;
background: none;
border: none;
border-bottom: 3px solid #fff;
color: #fff;
}
#minutes::placeholder{
color: #ddd;
font-size: 1.7rem;
}
.btn{
background-color: #fff;
border-radius: 4px;
border: none;
outline: none;
cursor: pointer;
padding: 0.8rem 1.7rem;
font-size: 1.2rem;
font-weight: 700;
}
.start{
color: #1f0;
}
.stop{
color: #E00;
}
#start, #stop, #continue{
display: none;
}
.counter{
color: #fff;
}
<!DOCTYPE html>
<html class="class2">
<head>
<title>CountDown</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
<header>
<h1>CountDown</h1>
</header>
<div class="content">
<div class="counter"></div>
<input type="number" id="minutes" placeholder="Minutes">
<div class="buttons">
<button class="btn start" id="start" value="1" onclick="check(this)">Start</button>
<button class="btn start" id="continue" value="1" onclick="check(this)">Continue</button>
<button class="btn stop" id="stop" value="0" onclick="check(this)">Stop</button>
<button class="btn start" id="ok" onclick="toSubmit()">Submit</button>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>

Checked is not a function javascript error

I am working on a simple To-Do list project. In this project you are able to add a task and once the user presses submit the task is shown along with a checkbox. When you click the checkbox, it's supposed to show an alert and make the tasks style decoration line-through.
I've tried many ways to accomplish this. The first way I tried work however it only worked on one task and for the others, it showed an error. I also tried making it work with an if statement but it's just showing the same error. I've tried switching a lot of things around (that's why my code looks so messy) but it just won't work.
var name = prompt("Please Enter Your Name :)");
document.write('<h1 id = "greet">' + 'Hello ' + name + ' Let\'s Be Productive Today' + '</h1>');
function showTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if (h == 0) {
h = 12;
}
if (h > 12) {
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
document.getElementById("b").onclick = function () {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function () {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("task");
document.getElementById("date");
document.getElementById("tsks");
document.getElementById("check");
document.getElementById("s").onclick = function () {
var newEl = document.createElement("p");
newEl.setAttribute("id", "tsks");
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'checked();'>" + task.value + ' ' + date.value;
document.getElementById('task2').appendChild(newEl);
}
function checked() {
if (check.onclick == true) {
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.value + "Good Job!");
}
}
body {
background-image: url("https://i.ibb.co/dLrp1gP/43150024-polka-dot-background-blue-vector-elegant-image.jpg");
}
.content {
background-color: white;
width: 700px;
height: 400px;
position: absolute;
left: 325px;
top: 150px;
}
#greet {
position: absolute;
left: 445px;
top: 150px;
background: -webkit-linear-gradient(#2980B9, #6DD5FA, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
#MyClockDisplay {
color: blue;
font-weight: bold;
position: absolute;
left: 625px;
top: 230px;
}
#b {
background-image: linear-gradient(#2980B9, #6DD5FA, #fff);
color: black;
border-color: white;
text-weight: bold;
width: 70px;
height: 50px;
position: absolute;
left: 625px;
top: 260px;
}
.To-Do {
width: 100%;
height: 100%;
position: absolute;
top: 0;
display: flex;
justify-content: center;
align-items: center;
display: none;
z-index: 1;
}
.modal-content {
width: 500px;
height: 300px;
border-radius: 10px;
position: relative;
background-color: purple;
}
.close {
position: absolute;
top: 0;
right: 14px;
font-size: 32px;
transform: rotate(45deg);
cursor: pointer;
}
#aat {
background-color: white;
font-weight: bold;
}
h2 {
position: absolute;
left: 590px;
top: 305px;
border-bottom: 5px solid blue;
}
p {
font-weight: bold;
position: relative;
left: 590px;
top: 360px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<h1 align = "center" id = "aat">ADD A TASK</h1>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
I'm not sure why, but within the scope of the onclick execution, checked is a local variable that contains the checkbox's clicked property.
There are several ways you can resolve this:
Rename the function so it doesn't conflict with this variable.
Call it as window.checked().
Assign the handler by assigning to the onclick property or calling addEventListener rather than putting it in the HTML.
I've chosen the last method.
Also, IDs should be unique, you can't reuse the IDs check and tsks for every task. You can refer to the box that was clicked on with this in the function, and the containing p element with this.parentElement.
A p element doesn't have a value property, use textContent to get the name of the task.
var name = prompt("Please Enter Your Name :)");
document.write('<h1 id = "greet">' + 'Hello ' + name + ' Let\'s Be Productive Today' + '</h1>');
function showTime() {
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if (h == 0) {
h = 12;
}
if (h > 12) {
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
document.getElementById("b").onclick = function () {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function () {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("task");
document.getElementById("date");
document.getElementById("tsks");
document.getElementById("check");
document.getElementById("s").onclick = function () {
var newEl = document.createElement("p");
newEl.innerHTML = "<input type = 'checkbox'>" + task.value + ' ' + date.value;
newEl.querySelector("input").addEventListener("click", checked);
document.getElementById('task2').appendChild(newEl);
}
function checked() {
if (this.checked) {
var tsks = this.parentElement;
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.innerText + "Good Job!");
}
}
body {
background-image: url("https://i.ibb.co/dLrp1gP/43150024-polka-dot-background-blue-vector-elegant-image.jpg");
}
.content {
background-color: white;
width: 700px;
height: 400px;
position: absolute;
left: 325px;
top: 150px;
}
#greet {
position: absolute;
left: 445px;
top: 150px;
background: -webkit-linear-gradient(#2980B9, #6DD5FA, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
#MyClockDisplay {
color: blue;
font-weight: bold;
position: absolute;
left: 625px;
top: 230px;
}
#b {
background-image: linear-gradient(#2980B9, #6DD5FA, #fff);
color: black;
border-color: white;
text-weight: bold;
width: 70px;
height: 50px;
position: absolute;
left: 625px;
top: 260px;
}
.To-Do {
width: 100%;
height: 100%;
position: absolute;
top: 0;
display: flex;
justify-content: center;
align-items: center;
display: none;
z-index: 1;
}
.modal-content {
width: 500px;
height: 300px;
border-radius: 10px;
position: relative;
background-color: purple;
}
.close {
position: absolute;
top: 0;
right: 14px;
font-size: 32px;
transform: rotate(45deg);
cursor: pointer;
}
#aat {
background-color: white;
font-weight: bold;
}
h2 {
position: absolute;
left: 590px;
top: 305px;
border-bottom: 5px solid blue;
}
p {
font-weight: bold;
position: relative;
left: 590px;
top: 360px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<h1 align = "center" id = "aat">ADD A TASK</h1>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
Hey it worked by changing if(check.onclick == true) to if(check.checked == true) and also function name from checked to chec, because checked is a property in java script . So this keyword cannot be used as function name.
var name = prompt("Please Enter Your Name :)");
document.write( '<h1 id = "greet">' + 'Hello ' + name + ' Let\'s Be Productive Today' + '</h1>');
function showTime(){
var date = new Date();
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
var session = "AM";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
setTimeout(showTime, 1000);
}
showTime();
document.getElementById("b").onclick = function() {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function() {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("task");
document.getElementById("date");
document.getElementById("tsks");
document.getElementById("check");
document.getElementById("s").onclick = function() {
var newEl = document.createElement("p");
newEl.setAttribute("id", "tsks" );
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'chec()'>" + task.value + ' ' + date.value;
document.getElementById('task2').appendChild(newEl);
}
function chec() {
if(check.checked == true) {
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.value + "Good Job!");
}
}
body {
background-image:url("https://i.ibb.co/dLrp1gP/43150024-polka-dot-background-blue-vector-elegant-image.jpg");
}
.content {
background-color:white;
width:700px;
height:400px;
position:absolute;
left:325px;
top:150px;
}
#greet {
position:absolute;
left:445px;
top:150px;
background: -webkit-linear-gradient(#2980B9, #6DD5FA, #fff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
#MyClockDisplay {
color:blue;
font-weight:bold;
position:absolute;
left:625px;
top:230px;
}
#b {
background-image:linear-gradient(#2980B9, #6DD5FA, #fff);
color:black;
border-color:white;
text-weight:bold;
width:70px;
height:50px;
position:absolute;
left:625px;
top:260px;
}
.To-Do {
width:100%;
height:100%;
position:absolute;
top:0;
display:flex;
justify-content:center;
align-items:center;
display:none;
z-index:1;
}
.modal-content {
width:500px;
height:300px;
border-radius:10px;
position:relative;
background-color:purple;
}
.close {
position:absolute;
top:0;
right:14px;
font-size:32px;
transform:rotate(45deg);
cursor:pointer;
}
#aat {
background-color:white;
font-weight:bold;
}
h2 {
position:absolute;
left:590px;
top:305px;
border-bottom:5px solid blue;
}
p {
font-weight:bold;
position:relative;
left:590px;
top:360px;
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<h1 align = "center" id = "aat">ADD A TASK</h1>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>
I got it to work by changing checked() to window.checked() and removing the if statement in side the checked function
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'window.checked()'>" + task.value + ' ' + date.value;
function checked() {
tsks.style.textDecoration = "line-through";
alert("You completed task" + tsks.value + "Good Job!");
}
Two points:
You have used function "checked" on the checkbox. It is the name of
property, so choose any other name
To change only selected
element - pass it to event handler.
Working example: https://jsfiddle.net/zordaxy/L0sbp8mt/27/
document.getElementById("b").onclick = function() {
document.querySelector(".To-Do").style.display = 'flex';
}
document.querySelector(".close").onclick = function() {
document.querySelector(".To-Do").style.display = 'none';
}
document.getElementById("s").onclick = function() {
var newEl = document.createElement("p");
newEl.setAttribute("id", "tsks" );
newEl.innerHTML = "<input type = 'checkbox' id = 'check' onclick = 'checked2(this);'>" + task.value + ' ' + date.value;
document.getElementById('task2').appendChild(newEl);
}
function checked2(item) {
console.log(item);
item.parentElement.style.textDecoration = "line-through";
}
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<div class = "content"></div>
<div id="MyClockDisplay" class="clock" onload="showTime()"></div>
<button id = "b">Add A Task</button>
<div class = "To-Do">
<div class = "modal-content">
<p align = "center" id = "aat" onclick='checked()'>ADD A TASK</p>
<input type = "text" placeholder = "task" id = "task">
<input type = "date" id = "date">
<div class = "close">+</div>
<input type = "submit" id = "s">
</div>
</div>
<div id = "task2"></div>
<h2>YOUR TASKS</h2>
</body>
</html>

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>

Categories

Resources