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>
Related
I have made 3 buttons (10 $, 20 $ ,50$)
and i want when someone clicks a button to add the previous value.
But i get something like this when i click on my buttons 1020502010
Something im doing wrong in this part of the code
// function betBtn()
function bet10 () {
chipbeted.textContent += betc.bet10
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet20 () {
chipbeted.textContent += betc.bet20
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet50 (){
chipbeted.textContent += betc.bet50
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
let player = {
Name : "Nik",
Chips: 150
}
let cards = []
let sum = 0
let hasBlackjack = false
let isAlive = false
let betOn = false
let betc ={
bet10 : 10,
bet20 : 20,
bet50 : 50
}
let message = ""
let messageEl = document.getElementById("message-el")
let totalBet = document.getElementById("chipCount").textContent
let sumEl = document.querySelector("#sum-el")
let cardsEl = document.getElementById("cards-el")
let chipbeted = document.getElementById("chipCount")
let playerEl = document.getElementById("playerEl")
playerEl.textContent = player.Name +":" +" " + player.Chips + "$"
console.log(cards)
function getRandomCard () {
let randomNumer = Math.floor( Math.random()*13 ) + 1
if (randomNumer > 10) {
return 10
} else if (randomNumer === 1) {
return 11
} else {
return randomNumer
}
}
let randomCard = getRandomCard()
function startGame (){
if (betOn === true){
isAlive = true
let firstCard = getRandomCard()
let secondCard = getRandomCard()
cards = [firstCard, secondCard]
sum = firstCard + secondCard
$('.class').css('visibility', 'hidden');
}
else if (betOn === false){
document.getElementById("messagewl").textContent = "First, select how many chips you want to BET"
sum= ""
}
renderGame()
}
function renderGame(){
cardsEl.textContent = "Cards: "
for ( let i=0; i<cards.length ; i++){
cardsEl.textContent += cards[i] + " "
}
sumEl.textContent = "Sum: " + sum
if ( sum <= 20) {
console.log(sum)
message = "Do you want to draw a new card? "
}
else if ( sum === 21){
console.log(sum)
message = "You've got Blackjack!"
hasBlackjack = true
}
else {
console.log(sum)
message = "You're out of the game!"
isAlive = false
}
messageEl.textContent = message
sumEl.textContent = "Sum: " + sum
}
function cardNew(){
if (isAlive === true && hasBlackjack === false) {
let card = getRandomCard()
sum += card
cards.push(card)
console.log(cards)
renderGame()
}
}
// function betBtn()
function bet10 () {
chipbeted.textContent += betc.bet10
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet20 () {
chipbeted.textContent += betc.bet20
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet50 (){
chipbeted.textContent += betc.bet50
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
html, body{
background-image: url("space.png");
background-size: cover;
background-attachment: fixed;
}
body {
color: aliceblue;
font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif ;
text-align: center;
margin-top: 30px;
}
#h1 {
text-align: center;
}
h1 {
font-size: 4em;
display: inline-block;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
border-radius: 100px;
border: 30px;
padding: 0 10px;
text-align: center;
}
#buttons {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 10px;
}
p{
font-size: 2em;
}
#btn {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
width:250px;
font-size: 2.5em;
color: aliceblue;
}
#btnBet > #btn10,#btn20,#btn50{
margin-top: 20px;
font-size: 30px;
font-weight: bold;
justify-content: center;
margin: 20 15 0 15;
}
<html lang="en">
<head>
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blackjac Game</title>
</head>
<body>
<div class="h1">
<h1>Space Blackjack</h1>
</div>
<p id="message-el">Want to play a round?</p>
<p id="cards-el">Cards:</p>
<p id="sum-el">Sum:</p>
<p class= "class" id="messagewl"></p>
<div id="buttons">
<button id="btn" onclick="startGame()">Start Game</button>
<button id="btn" onclick="cardNew()">Draw Card</button>
<button id="btn" onclick="bet()">Bet Chips</button>
</div>
<div id="btnBet">
<button id="btn10" onclick="bet10()">10$</button>
<button id="btn20" onclick="bet20()">20$</button>
<button id="btn50" onclick="bet50()">50$</button>
</div>
<p id="chipCount"></p>
<p id="playerEl"></p>
<script src="index.js"></script>
</body>
This is happening because the variable chipbeted.textContent returns a string .. that's why you get concatenated result (for example: '20'+10 = 2010 not 30
)..
to solve this problem,
let chipbeted = document.getElementById("chipCount")
let betc = {
bet10: 10,
bet20: 20,
bet50: 50
}
function bet20() {
chipbeted.textContent = Number(chipbeted.textContent) + betc.bet20
//betOn = true
//$('.class').css('visibility', 'hidden');
//console.log(chipbeted.textContent)
}
<button onClick="bet20()">Add bet20</button>
<p id="chipCount"></p>
replace
chipbeted.textContent += betc.bet20
in your functions
with
chipbeted.textContent = Number(chipbeted.textContent) + betc.bet20
Salam . Try this in your function betBtn() :
chipbeted.textContent=parseInt(chipbeted.textContent)+betc.betBtn ;
Instead of this :
chipbeted.textContent += betc.betBtn
You have to convert the text fields value to Number first, than add the value to it. Otherwise the "+" operator means string concatenation.
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet20
let player = {
Name : "Nik",
Chips: 150
}
let cards = []
let sum = 0
let hasBlackjack = false
let isAlive = false
let betOn = false
let betc ={
bet10 : 10,
bet20 : 20,
bet50 : 50
}
let message = ""
let messageEl = document.getElementById("message-el")
let totalBet = document.getElementById("chipCount").textContent
let sumEl = document.querySelector("#sum-el")
let cardsEl = document.getElementById("cards-el")
let chipbeted = document.getElementById("chipCount")
let playerEl = document.getElementById("playerEl")
playerEl.textContent = player.Name +":" +" " + player.Chips + "$"
console.log(cards)
function getRandomCard () {
let randomNumer = Math.floor( Math.random()*13 ) + 1
if (randomNumer > 10) {
return 10
} else if (randomNumer === 1) {
return 11
} else {
return randomNumer
}
}
let randomCard = getRandomCard()
function startGame (){
if (betOn === true){
isAlive = true
let firstCard = getRandomCard()
let secondCard = getRandomCard()
cards = [firstCard, secondCard]
sum = firstCard + secondCard
$('.class').css('visibility', 'hidden');
}
else if (betOn === false){
document.getElementById("messagewl").textContent = "First, select how many chips you want to BET"
sum= ""
}
renderGame()
}
function renderGame(){
cardsEl.textContent = "Cards: "
for ( let i=0; i<cards.length ; i++){
cardsEl.textContent += cards[i] + " "
}
sumEl.textContent = "Sum: " + sum
if ( sum <= 20) {
console.log(sum)
message = "Do you want to draw a new card? "
}
else if ( sum === 21){
console.log(sum)
message = "You've got Blackjack!"
hasBlackjack = true
}
else {
console.log(sum)
message = "You're out of the game!"
isAlive = false
}
messageEl.textContent = message
sumEl.textContent = "Sum: " + sum
}
function cardNew(){
if (isAlive === true && hasBlackjack === false) {
let card = getRandomCard()
sum += card
cards.push(card)
console.log(cards)
renderGame()
}
}
// function betBtn()
function bet10 () {
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet10;
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet20 () {
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet20 ;
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet50 (){
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet50;
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
html, body{
background-image: url("space.png");
background-size: cover;
background-attachment: fixed;
}
body {
color: aliceblue;
font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif ;
text-align: center;
margin-top: 30px;
}
#h1 {
text-align: center;
}
h1 {
font-size: 4em;
display: inline-block;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
border-radius: 100px;
border: 30px;
padding: 0 10px;
text-align: center;
}
#buttons {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 10px;
}
p{
font-size: 2em;
}
#btn {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
width:250px;
font-size: 2.5em;
color: aliceblue;
}
#btnBet > #btn10,#btn20,#btn50{
margin-top: 20px;
font-size: 30px;
font-weight: bold;
justify-content: center;
margin: 20 15 0 15;
}
<html lang="en">
<head>
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blackjac Game</title>
</head>
<body>
<div class="h1">
<h1>Space Blackjack</h1>
</div>
<p id="message-el">Want to play a round?</p>
<p id="cards-el">Cards:</p>
<p id="sum-el">Sum:</p>
<p class= "class" id="messagewl"></p>
<div id="buttons">
<button id="btn" onclick="startGame()">Start Game</button>
<button id="btn" onclick="cardNew()">Draw Card</button>
<button id="btn" onclick="bet()">Bet Chips</button>
</div>
<div id="btnBet">
<button id="btn10" onclick="bet10()">10$</button>
<button id="btn20" onclick="bet20()">20$</button>
<button id="btn50" onclick="bet50()">50$</button>
</div>
<p id="chipCount"></p>
<p id="playerEl"></p>
<script src="index.js"></script>
</body>
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>
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>
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>
I'm generating primes, and it will lag until it's done. Is there a way where I can make it so it doesn't lag. For example, if you're generating up to 1000, I want it to just spit out the answers right away when it's done calculating the number.
HTML:
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>Prime Generator</title>
<h1>
Welcome to my online prime generator!
<h1>
<style>
.w3-gold,.w3-hover-gold:hover{color:#fff!important;background-color:#c9a000!important}
.w3-btn {
background-color: #c9a000;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 0px;
-webkit-transition-duration: 0.4s;
transition-duration: 0.4s;
cursor: pointer;
float: right;
}
}
.button1 {
background-color: black;
color: white;
}
.button1:hover {
background-color: #e7e7e7;
color: black
}
.button2 {
background-color: #c9a000;
color: white;
}
.button2:hover {
background-color: #e7e7e7;
color: black
}
</style>
</head>
<body>
<div class="w3-container">
<div class="w3-card-4">
<div class="container w3-gold">
<h2>Input Form</h2>
</div>
<form class="w3-container">
<p>
<select class="w3-select" name="option" id="option">
<option value="" disabled selected>Generate or Choose?</option>
<option value="1" >Generate</option>
<option value="2" >Choose</option>
</select>
<input class="w3-input" id="inputt" type="text">
<label class="w3-text">Type in a number<label>
</p>
<p>
<div class="w3-btn button2" id="BT2">Clear</div>
<div class="w3-btn button1" id="BT1">Proceed</div>
<div id ="done"></div>
<div id="out"></div>
<div id="gout"></div>
</form>
<script>
function prime(num) {
var stop = num % 2 == 0
var num1 = 2
var num2 = 2
while (stop == false && num2 <= Math.sqrt(num)) {
stop = num1 * num2 == num
num1++
if (num1 == num) {
num1 = 2
num2++
}
}
if (stop == true) {
return(num + " is not prime.")
} else {
return(num + " is prime")
}
}
document.getElementById("BT1").addEventListener("click", function(){
if (isNaN(document.getElementById("inputt").value) == false && document.getElementById("inputt").value != "" && document.getElementById("option").value == 1) {
document.getElementById("out").innerHTML = "<br> Generating up to " + document.getElementById("inputt").value + "!"
document.getElementById("gout").innerHTML = ""
for (num3 = 1; num3 <= parseInt(document.getElementById("inputt").value); num3++) {
document.getElementById("gout").innerHTML = document.getElementById("gout").innerHTML + "<br>" + prime(num3)
}
document.getElementById("done").innerHTML = "done!"
} else if (isNaN(document.getElementById("inputt").value) == false && document.getElementById("inputt").value != "" && document.getElementById("option").value == 2) {
document.getElementById("out").innerHTML = "Checking if " + document.getElementById("inputt").value + " is prime!"
document.getElementById("gout").innerHTML = "<br>" + prime(parseInt(document.getElementById("inputt").value))
} else if (document.getElementById("inputt").value != "") {
document.getElementById("out").innerHTML = document.getElementById("inputt").value + " is not a number!"
} else {
document.getElementById("out").innerHTML = "Thats a blank space!"
}
});
document.getElementById("BT2").addEventListener("click", function(){
document.getElementById("gout").innerHTML = ""
document.getElementById("out").innerHTML = ""
document.getElementById("done").innerHTML = ""
});
</script>
</div>
</div>
</body>
</html>
For an immediate fix, you can replace the contents of the for loop with the following:
var pr = prime(num3);
var cont = document.createTextNode(pr);
var br = document.createElement('br');
document.getElementById("gout").appendChild(br);
document.getElementById("gout").appendChild(cont);
The reason for the lag is that setting innerHTML is a very time taking operation, I guess.