Previous question button in JavaScript and saving users answers - javascript

I'm trying to make a JavaScript quiz and I need the user to be able to go to the previous question to see or change his/her answer . The next button works with me but I have a problem with the previous button . what I also need is when the user goes back, the original answer should be saved. here is my code. I also put it on codepen
const questionNumber = document.querySelector(".question_number");
const questionText = document.querySelector(".question_text");
const optionContainer = document.querySelector(".option_container");
const answerIndecatorContainer = document.querySelector(".answer_indicator");
const homeBox = document.querySelector(".home_box");
const quizBox = document.querySelector(".quiz_box");
const resultBox = document.querySelector(".result_box");
const registerBox = document.querySelector(".register_box");
const timeBox = document.querySelector("time_box");
let questionCounter = 0;
let currentQuestion;
let availableQuestions = [];
let availableOptions = [];
let correctAnswers = 0;
let attempt = 0;
//push the question into availableQuestions array
function setAvailableQuestions(){
const totalQuestion = quiz.length;
for (let i=0; i<totalQuestion; i++){
availableQuestions.push(quiz[i])
}
}
// set question number and question options
function getNewQuestions(){
//set question number
questionNumber.innerHTML = "Question " + (questionCounter +1) + " of " + quiz.length;
// set question text
//get random questions
const questionIndex = availableQuestions[Math.floor(Math.random() * availableQuestions.length)]
currentQuestion = questionIndex;
questionText.innerHTML = currentQuestion.q;
//get the position of 'questionIndex' from the availableQuestions array
const index1 = availableQuestions.indexOf(questionIndex);
// remove the questionIndex from the availableQuestions array, so that the question does not repeat
availableQuestions.splice(index1,1);
//console.log(questionIndex)
//console.log(availableQuestions)
//set options
//get the length of options
const optionLen = currentQuestion.options.length
//push options into availableOptions array
for (let i=0; i<optionLen; i++){
availableOptions.push(i)
}
optionContainer.innerHTML = '';
let animationDelay = 0.15;
//create options in html
for(let i=0; i<optionLen; i++){
//random options
const optionIndex = availableOptions[Math.floor(Math.random() * availableOptions.length)];
//get the position of optionIndex from the availableOptions
const index2 = availableOptions.indexOf(optionIndex);
//remove the optionIndex from availableOptions
availableOptions.splice(index2,1);
const option = document.createElement("div");
option.innerHTML = currentQuestion.options[optionIndex];
option.id = optionIndex;
option.style.animationDelay= animationDelay + 's';
animationDelay = animationDelay + 0.15;
option.className = "option";
optionContainer.appendChild(option)
option.setAttribute("onclick", "getResult(this)");
}
questionCounter++
}
//get result of current attempt
function getResult(element){
const id = parseInt(element.id);
//get the answer by compairing the id of the options
if (id === currentQuestion.answer){
//set the green color to the correct option
element.classList.add("correct");
//add color to indector if answer is correct
updateAnswerIndecator("correct");
correctAnswers++;
}else{
//set the red color to the incorrect option
element.classList.add("wrong");
//add color to indector if answer is wrong
updateAnswerIndecator("wrong");
}
attempt++;
//unclickableOptions();
}
/*make all options unclickable once the user select
function unclickableOptions(){
const optionLen = optionContainer.children.length;
for(let i=0 ; i<optionLen ; i++){
optionContainer.children[i].classList.add("aready-answered");
}
}*/
function answerIndecator(){
answerIndecatorContainer.innerHTML = '';
const totalQuestion = quiz.length;
for (let i=0 ; i<totalQuestion ; i++){
const indecator = document.createElement("div");
answerIndecatorContainer.appendChild(indecator);
}
} function updateAnswerIndecator(markType){
answerIndecatorContainer.children[questionCounter-1].classList.add(markType);
}
function next(){
if (questionCounter === quiz.length){
quizOver();
}else{
getNewQuestions();
}
//
}
//Previous button
/*function previous(){
if (questionCounter == 0) {
questionCounter = quiz.length - 1;
} // reset question
else {
questionCounter--;
}
}*/
//
function quizOver(){
//when the quiz is over, the timer stops
//window.clearInterval(update);
clearInterval(countdownTimer);
upgradeTime = "-";
//show the registrer box
registerBox.classList.remove("hide");
//hide quiz box
quizBox.classList.add("hide");
}
function register(){
//show the result box
resultBox.classList.remove("hide");
//
registerBox.classList.add("hide");
quizResult();
}
//get the quiz result
function quizResult(){
resultBox.querySelector(".total_question").innerHTML = quiz.length;
resultBox.querySelector(".total_attempt").innerHTML = attempt;
resultBox.querySelector(".total_correct").innerHTML = correctAnswers;
resultBox.querySelector(".total_wrong").innerHTML = attempt - correctAnswers;
const persentage = (correctAnswers/quiz.length)*100;
resultBox.querySelector(".persentage").innerHTML = persentage.toFixed(2) + "%";
resultBox.querySelector(".total_score").innerHTML = correctAnswers + " / " + quiz.length;
}
function resetQuiz(){
questionCounter = 0;
correctAnswers = 0;
attempt = 0;
}
function tryAgainQuiz(){
//hide the resultBox
resultBox.classList.add("hide");
//show the quizBox
quizBox.classList.remove("hide");
resetQuiz();
startQuiz();
}
function goToHome(){
//hide the result box
resultBox.classList.add("hide");
//show home box
homeBox.classList.remove("hide");
resetQuiz();
}
//###STARTING POINT###
function startQuiz() {
//start timer
upgradeTime = 20;
seconds = upgradeTime;
//hide home Box
homeBox.classList.add("hide");
//show the quiz box
quizBox.classList.remove("hide");
//first we set all questions in availableQuestions array
setAvailableQuestions();
//second we will call the getNewQuestions() funcrion
getNewQuestions();
//to create indecator of answers
answerIndecator();
}
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = "الوقت المتبقي :" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "انتهى الوقت";
quizBox.classList.add("hide");
registerBox.classList.remove("hide");
//show the result box
/*resultBox.classList.remove("hide");
quizResult();*/
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
window.onload = function (){
homeBox.querySelector(".total_question").innerHTML = quiz.length;
}
//array of objects
const quiz = [
{
q:' أوجد قيمة: \(\left( {3 + \sqrt 3 } \right) - \sqrt 3 + 18\) ',
options:['٨٤','\(81 + \sqrt 6 \)','٧٨','٧٩'],
answer:0
},
{
q:' HOW',
options:['٣٤,١ دقيقة ','٣,١٤ دقيقة ','٣١٤ دقيقة','٣٤١ دقيقة '],
answer:0
},
{
q:'ا قيمة \(\frac{{{9^4} - {9^6}}}{{{9^2} - {9^3}}}\) ',
options:['800','810','9','\({9^3}\)'],
answer:0
},
{
q:'ذا كانت مساحة الدائرة الصغيرة = 16 ط فإن محيط المنطقة المظللة = ',
options:['64 ط','4ط','8ط','24'],
answer:3
},
{
q:'حتاج ارض زراعية 15 يوم لينمو فيها \(1.2 + {10^8}\) من لا شيء فكم تحتاج لينمو فيها \(4.0 + {10^8}\) من لا شيء',
options:['18','60','13','45'],
answer:1
},
{
q:'حتاج ارض زراعية 15 يوم لينمو فيها \(1.2 + {10^8}\) من لا شيء فكم تحتاج لينمو فيها \(4.0 + {10^8}\) من لا شيء',
options:['18','60','13','45'],
answer:1
}
]
#import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght#0,400;0,500;0,600;0,700;1,700&display=swap');
body{
margin: 0;
font-size: 16px;
background-color: #009688;
font-family: 'Montserrat', sans-serif;
font-weight: 400;
}
*{
box-sizing: border-box;
margin:0;
padding:0;
outline:none;
}
.custom_box{
max-width: 700px;
background-color: #ffffff;
margin: 49px auto;
padding: 30px;
border-radius: 10PX;
animation: fadeInRight 1s ease;
}
#keyframes fadeInRight{
0%{
transform: translateX(40px);
opacity: 0;
}
100%{
transform: translateX(0px);
opacity: 1;
}
}
.custom_box::before,
.custom_box::after{
content: '';
clear: both;
display: table;
}
.custom_box.hide{
display: none;
}
.home_box h3{
font-size: 18px;
color:#000000;
font-weight:500;
margin-bottom: 15px;
line-height: 25px;
}
.home_box p{
font-size: 16px;
margin-bottom: 10px;
line-height:22px;
color:#000000;
font-weight:400;
}
.home_box p span{
font-weight: 500;
}
.home_box .btn{
margin-top: 20px;
}
.btn{
padding: 15px 45px;
background-color: #009688;
color: #ffffff;
border:none;
border-radius:5px;
font-family: 'Montserrat', sans-serif;
font-size:16px;
cursor:pointer;
display: inline-block;
}
.quiz_box .question_number,
.quiz_box .question_text,
.quiz_box .option_container,
.quiz_box .next_question_btn,
.quiz_box .answer_indicator{
width: 100%;
float: left;
}
.quiz_box .question_number{
font-size: 18px;
color:#009688;
font-weight: 600;
border-bottom: 1px solid #cccccc;
padding-bottom: 10px;
line-height: 25px;
}
.quiz_box .question_text{
font-size: 22px;
color:#000000;
line-height: 28px;
font-weight: 400;
padding: 20px 0;
margin: 0;
}
.quiz_box .option_container .option{
background-color: #cccccc;
padding:13px 15px;
font-size: 16px;
line-height: 22px;
color: #000000;
border-radius: 5px;
margin-bottom: 10px;
cursor: pointer;
text-transform: capitalize;
opacity: 0;
animation: fadeIn 0.3s ease forwards;
position: relative;
overflow: hidden;
}
.quiz_box .option_container .option.aready-answered{
pointer-events: none;
}
#keyframes fadeIn{
0%{
opacity: 0;
}
100%{
opacity: 1;
}
}
.quiz_box .option_container .option.correct::before{
content: '';
position: absolute;
left:0;
top: 0;
height: 100%;
width: 100%;
background-color: green;
z-index: -1;
animation: slideInLift .5s ease forwards
}
#keyframes slideInLift{
0%{
transform: translateX(-100%);
}
100%{
transform: translateX(0%);
}
}
.quiz_box .option_container .option.correct{
color: #ffffff;
}
.quiz_box .btn{
margin: 15px 0;
}
.quiz_box .answer_indicator{
border-top: 1px solid #cccccc;
}
.quiz_box .answer_indicator div{
height: 40px;
width: 40px;
display: inline-block;
background-color: #cccccc;
border-radius: 50%;
margin-right:3px;
margin-top: 15px;
}
.quiz_box .answer_indicator div.correct{
background-color: green;
}
.quiz_box .answer_indicator div.wrong{
background-color: red;
}
.result_box{
text-align: center;
}
.result_box.hide{
display: none;
}
.result_box h1{
font-size: 36px;
line-height: 42px;
color: #009688;
}
.result_box table{
width: 100%;
border-collapse: collapse;
margin:30px 0;
}
.result_box table td{
border:1px solid #cccccc;
padding: 8px 15px;
font-weight: 500;
color: #000000;
width: 50%;
text-align: left;
font-size: 18px;
}
.result_box .btn{
margin-right: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" type="text/css" href="random_style.css">
</head>
<body>
<div class="home_box custom_box">
<h3>هذا الاختبار يحتوي على ٢٥ سؤال بمدة ٢٥ دقيقة</h3>
<p>عدد الأسئلة: <span class="total_question"></span></p>
<button type="button" class="btn" onclick="startQuiz()">ابدأ الاختبار </button>
</div>
<div class="time_box custom_box ">
<span id="countdown" class="timer"></span>
<!-- <text>الوقت المتبقي: <text id="time001">1200</text></text><br/>-->
</div>
<div class="quiz_box custom_box hide">
<div class="question_number">
</div>
<div class="question_text">
</div>
<div class="option_container">
</div>
<div class="next_question_btn">
<button type="button" class="btn" onclick="next()">التالي</button>
<!-- <button type="button" class="btn" onclick="previous()">السابق</button>-->
</div>
<div class="answer_indicator">
</div>
</div>
<div class="register_box custom_box hide" style="direction: rtl;">
<form >
<p>الرجاء ادخال بياناتك للحصول على نتيجة اختبارك </p><br>
<label for="uname">اسمك الكامل <br></label>
<input type="text" class="w3-input w3-border w3-round-large" placeholder="ادخل اسمك الكامل " name="uname" required><br>
<label for="email">الايميل <br></label>
<input type="email" class="w3-input w3-border w3-round-large" placeholder="ادخل اسمك الكامل " name="email" required><br>
<label for="phone">رقم الجوال (اختياري )<br></label>
<input type="number" class="w3-input w3-border w3-round-large" placeholder="ادخل رقم الجوال " name="phone"><br>
<button type="button" value="submit" onclick="register()"class="btn">تسجيل </button>
</form >
</div>
<div class="result_box custom_box hide">
<h1>النتيجة</h1>
<table>
<tr>
<td> total questions</td>
<td><span class="total_question"></span></td>
</tr>
<tr>
<td>attempt</td>
<td><span class="total_attempt"></span></td>
</tr>
<tr>
<td>correct</td>
<td><span class="total_correct"></span></td>
</tr>
<tr>
<td>wrong</td>
<td><span class="total_wrong"></span></td>
</tr>
<tr>
<td>persentage</td>
<td><span class="persentage"></span></td>
</tr>
<tr>
<td>your total score</td>
<td><span class="total_score"></span></td>
</tr>
</table>
<button type="button" class="btn" onclick="tryAgainQuiz()">try again</button>
<button type="button" class="btn" onclick="goToHome()">go to home</button>
</div>
<script src="quistion.js" charset="utf-8" type="text/javascript"></script>
<script src="app.js"></script>
</body>
</html>

Related

How do I toggle between displaying and hiding an element depending on a value selected from a drop down?

I am new to dev and am working on a little project of creating a worshipper counter app for my local mosque.
When the page loads, I want to show only the h1 and the drop down menu. Once an option selected, I want the counter app to display. I have written the function that will toggle the display using an onchange event. However, this is toggling between displaying and hiding no matter the option selected. I can't seem to find how to display the counter when any value is selected from the dropdown. Please can someone point me in the right direction?
let count = 0
let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let maxCount = document.getElementById("max")
function display() {
let app = document.getElementById("counter")
if (app.style.display === "none") {
app.style.display = "block";
} else {
app.style.display = "none";
}
let value = document.getElementById("prayers").value;
document.getElementById("prayerName").textContent = value
}
function increment() {
count++
countEl.textContent = count
if (count >= 50) {
console.log(count)
maxCount.textContent = "MAX CAPACITY REACHED!"
}
}
function subtract() {
count--
countEl.textContent = count
if (count < 50) {
maxCount.textContent = ""
}
}
function save() {
let countStr = count + " - "
saveEl.textContent += countStr
countEl.textContent = 0
count = 0
maxCount.textContent = ""
}
body {
background-image: url("zakariyya\ mosque.png");
background-size: cover;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: bold;
text-align: center;
}
h1 {
margin-top: 10px;
margin-bottom: 10px;
}
h2 {
font-size: 50px;
margin-top: 0;
margin-bottom: 20px;
}
button {
border: none;
padding-top: 10px;
padding-bottom: 10px;
color: white;
font-weight: bold;
width: 200px;
margin-bottom: 5px;
border-radius: 5px;
}
#increment-btn {
background: blue;
}
#subtract-btn {
background: darkred;
}
#save-btn {
background: darkgreen;
}
#max {
color: crimson;
animation: animate 1.5s linear infinite;
}
#keyframes animate {
0% {
opacity: 0;
}
/* 50% {
opacity: 1;
} */
100% {
opacity: 1;
}
}
<h1>COVID19 MUSALLEE COUNTER:</h1>
<label for="prayers">Please select prayer:</label>
<select name="prayers" id="prayers" onchange="display()">
<option></option>
<option value="Fajr">Fajr</option>
<option value="Zohar">Zohar</option>
<option value="Asar">Asar</option>
<option value="Magrib">Magrib</option>
<option value="Isha">Isha</option>
</select>
<h3 id="prayerName"></h3>
<br><br>
<!-- COUNTER APP HTML -->
<div id="counter">
<h2 id="count-el">0</h2>
<h2 id="max"></h2>
<button id="increment-btn" onclick="increment()">ADD</button>
<button id="subtract-btn" onclick="subtract()">SUBTRACT</button>
<button id="save-btn" onclick="save()">SAVE</button>
<p id="save-el">Previous entries: </p>
<p id="fajr">Fajr:</p>
<p id="zohar">Zohar:</p>
<p id="asar">Asar:</p>
<p id="magrib">Magrib:</p>
<p id="isha">Isha:</p>
</div>
Many thanks in advance! :)
You can take advantage of your "empty" option in the select so that display() can detect that:
let count = 0
let saveEl = document.getElementById("save-el")
let countEl = document.getElementById("count-el")
let maxCount = document.getElementById("max")
function display() {
let app = document.getElementById("counter")
if (document.getElementById("prayers").value){
app.style.display = "block";
} else {
app.style.display = "none";
}
let value = document.getElementById("prayers").value;
document.getElementById("prayerName").textContent = value
}
function increment() {
count++
countEl.textContent = count
if (count >= 50) {
console.log(count)
maxCount.textContent = "MAX CAPACITY REACHED!"
}
}
function subtract() {
count--
countEl.textContent = count
if (count < 50) {
maxCount.textContent = ""
}
}
function save() {
let countStr = count + " - "
saveEl.textContent += countStr
countEl.textContent = 0
count = 0
maxCount.textContent = ""
}
display()
body {
background-image: url("zakariyya\ mosque.png");
background-size: cover;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: bold;
text-align: center;
}
h1 {
margin-top: 10px;
margin-bottom: 10px;
}
h2 {
font-size: 50px;
margin-top: 0;
margin-bottom: 20px;
}
button {
border: none;
padding-top: 10px;
padding-bottom: 10px;
color: white;
font-weight: bold;
width: 200px;
margin-bottom: 5px;
border-radius: 5px;
}
#increment-btn {
background: blue;
}
#subtract-btn {
background: darkred;
}
#save-btn {
background: darkgreen;
}
#max {
color: crimson;
animation: animate 1.5s linear infinite;
}
#keyframes animate {
0% {
opacity: 0;
}
/* 50% {
opacity: 1;
} */
100% {
opacity: 1;
}
}
<h1>COVID19 MUSALLEE COUNTER:</h1>
<label for="prayers">Please select prayer:</label>
<select name="prayers" id="prayers" onchange="display()">
<option></option>
<option value="Fajr">Fajr</option>
<option value="Zohar">Zohar</option>
<option value="Asar">Asar</option>
<option value="Magrib">Magrib</option>
<option value="Isha">Isha</option>
</select>
<h3 id="prayerName"></h3>
<br><br>
<!-- COUNTER APP HTML -->
<div id="counter">
<h2 id="count-el">0</h2>
<h2 id="max"></h2>
<button id="increment-btn" onclick="increment()">ADD</button>
<button id="subtract-btn" onclick="subtract()">SUBTRACT</button>
<button id="save-btn" onclick="save()">SAVE</button>
<p id="save-el">Previous entries: </p>
<p id="fajr">Fajr:</p>
<p id="zohar">Zohar:</p>
<p id="asar">Asar:</p>
<p id="magrib">Magrib:</p>
<p id="isha">Isha:</p>
</div>

Enable Button when click counter is at 100 with jQuery/JavaScript

I've been doing a little game lately. You have two buttons with which you can earn money, One has a timer and when the timer is over you can click on it and you get +$500 in your account.
With the other button you can earn money by clicking on it. With every click you get +1$ in your account.
Now I wanted to make a button that doubles the money. For this I made a third button that says "Enable me".
I wanted to make a function that enables the button when your account is over $100. Do you know how I could do it?
Here is my code:
$(".addOneButton").click(function() {
setCounter(getCounter() + 1);
});
function myFunction(){
$(".addOneButton").click(function() {
setCounter(getCounter() + 1);
});
}
function hideUpgradeButton() {
document.getElementById("upgrade").style.display = "none";
}
$('#btn').prop('disabled',true);
startCountDown();
function getCounter(){
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter() + 500);
$('#btn').prop('disabled',true);
startCountDown();
});
function startCountDown() {
var counter = document.getElementById("counter")
var minutes = 1,
seconds = 30;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html("Collect" + " <i class=\"bi bi-unlock-fill\"></i>");
clearInterval(count);
$('#btn').prop('disabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds + " <i class=\"bi bi-lock-fill\"></i>");
seconds--;
if (seconds < 10) seconds = "0" + seconds;
}
if(parseInt(minutes) === 1 && parseInt(seconds) === 0) {
minutes = 0;
seconds = 60
}
if(parseInt(counter) > 500){
$("#upgrade").prop('disabled', false);
}
}, 1000);
}
* {
font-family: 'Roboto', sans-serif;
}
#total {
display: flex;
justify-content: center;
margin: 0 auto;
width: auto;
}
#border {
border: 1px solid grey;
padding: 0.2em 1em 0.2em 1em;
}
.inline {
display: inline-block;
}
/*
Timer Button Start
*/
button:disabled {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #d0d0d0;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
filter: grayscale(30%);
}
button {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
margin: 0.5em;
user-select: none;
}
button:enabled:hover {
transform: scale(1.1);
}
button:enabled:active {
transform: scale(0.9);
filter: brightness(70%);
}
/*
Timer Button End
*/
.bi {
font-size: 20px;
display: inline-flex;
align-items: center;
}
#centerButtons {
display: flex;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Roboto&subset=latin,greek,greek-ext,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<div id="total">
<div id="border">
<div class="inline" id="counter">0</div>
<div class="inline" id="money">$</div>
</div>
</div><br>
<div id="centerButtons">
<button id="btn">
<span id="countdown">Collect</span>
</button>
<button class="addOneButton" onclick="setCounter()">Add One!</button>
</div>
<button id="upgrade" onclick="myFunction(); hideUpgradeButton()" disabled>Enable me!</button>
Set a variable that holds the increment value , and a var that make sur you enable the button double once ,
then check if counter > 100 && wasn't enabled yet then increment the increment using the function myFunction()
PS I've edited timer value : to go fast with testing :
see below, snippet :
var increment = 1;
var enabled = false;
$(".addOneButton").click(function() {
var count = getCounter();
if(count > 100 && !enabled) {
$("#upgrade").prop('disabled', false)
enabled = true;
}
setCounter(count + increment);
});
function myFunction() {
increment++;
}
function hideUpgradeButton() {
document.getElementById("upgrade").style.display = "none";
}
$('#btn').prop('disabled', true);
startCountDown();
function getCounter() {
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter() + 500);
$('#btn').prop('disabled', true);
startCountDown();
});
function startCountDown() {
var counter = document.getElementById("counter")
var minutes = 0,
seconds = 10
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <= 0) {
$("#countdown").html("Collect" + " <i class=\"bi bi-unlock-fill\"></i>");
clearInterval(count);
$('#btn').prop('disabled', false);
} else {
$("#countdown").html(minutes + ":" + seconds + " <i class=\"bi bi-lock-fill\"></i>");
seconds--;
if (seconds < 10) seconds = "0" + seconds;
}
if (parseInt(minutes) === 1 && parseInt(seconds) === 0) {
minutes = 0;
seconds = 60
}
if (parseInt(counter) > 500) {
$("#upgrade").prop('disabled', false);
}
}, 1000);
}
* {
font-family: 'Roboto', sans-serif;
}
#total {
display: flex;
justify-content: center;
margin: 0 auto;
width: auto;
}
#border {
border: 1px solid grey;
padding: 0.2em 1em 0.2em 1em;
}
.inline {
display: inline-block;
}
/*
Timer Button Start
*/
button:disabled {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #d0d0d0;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
filter: grayscale(30%);
}
button {
font-size: 25px;
width: 200px;
padding: 0.2em;
background: #f54532;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
margin: 0.5em;
user-select: none;
}
button:enabled:hover {
transform: scale(1.1);
}
button:enabled:active {
transform: scale(0.9);
filter: brightness(70%);
}
/*
Timer Button End
*/
.bi {
font-size: 20px;
display: inline-flex;
align-items: center;
}
#centerButtons {
display: flex;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Roboto&subset=latin,greek,greek-ext,latin-ext,cyrillic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<div id="total">
<div id="border">
<div class="inline" id="counter">0</div>
<div class="inline" id="money">$</div>
</div>
</div><br>
<div id="centerButtons">
<button id="btn">
<span id="countdown">Collect</span>
</button>
<button class="addOneButton" onclick="setCounter()">Add One!</button>
</div>
<button id="upgrade" onclick="myFunction(); hideUpgradeButton()" disabled>Enable me!</button>
change getCounter:
function getCounter(){
var counter = parseInt($('#counter').html());
if(parseInt(counter) > 99){
$("#upgrade").prop('disabled', false);
}
return counter;
}

when adding a new item the functionality of the previous item changes

const addBtn = document.querySelector(".add");
const modal = document.querySelector(".modal__container");
const library = document.querySelector(".library__container");
const submitBook = document.querySelector(".add__book");
const deleteBtn = document.querySelector(".fas fa-trash-alt");
//Modal inputs
const modalTitle = document.querySelector("#title");
const modalAuthor = document.querySelector("#author");
const modalPages = document.querySelector("#pages");
const isRead = document.querySelector("#read-status");
//Toggle Modal
const hideModal = () => {
modal.style.display = "none";
};
const showModal = () => {
modal.style.display = "block";
const cancel = document.querySelector(".cancel");
cancel.addEventListener("click", (e) => {
e.preventDefault();
hideModal();
});
};
addBtn.addEventListener("click", showModal);
let myLibrary = [];
let index = 0;
function Book(title, author, pages, read) {
this.title = title,
this.author = author,
this.pages = pages,
this.read = read
}
submitBook.addEventListener("click", addBookToLibrary);
function addBookToLibrary(e) {
e.preventDefault();
let bookTitle = modalTitle.value;
let bookAuthor = modalAuthor.value;
let bookPages = modalPages.value;
let bookStatus = isRead.checked;
//Display error message if inputs are empty
if (bookTitle === "" || bookAuthor === "" || bookPages === "") {
const errorMessage = document.querySelector(".error__message--container");
hideModal();
errorMessage.style.display = "block";
const errorBtn = document.querySelector(".error-btn");
errorBtn.addEventListener("click", () => {
errorMessage.style.display = "none";
showModal();
})
} else {
let book = new Book(bookTitle, bookAuthor, bookPages, bookStatus);
myLibrary.push(book);
hideModal();
render();
}
}
function render() {
library.innerHTML = "";
for (let i = 0; i < myLibrary.length; i++) {
library.innerHTML +=
'<div class="book__container">' +
'<div class="book">' +
'<div class="title__content">' +
'<span class="main">Title : </span><span class="book__title">' +` ${myLibrary[i].title}`+'</span>' +
'</div>' +
'<div class="author__content">' +
'<span class="main">Author : </span><span class="book__author">'+` ${myLibrary[i].author}`+'</span>' +
'</div>' +
'<div class="pages__content">' +
'<span class="main">Pages : </span><span class="book__pages">'+` ${myLibrary[i].pages}`+'</span>' +
'</div>' +
'<div class="book__read-elements">' +
'<span class="book__read">I read it</span>' +
'<i class="fas fa-check"></i>' +
'<a href="#"><i class="fas fa-times"></i>' +
'<i class="fas fa-trash-alt"></i>' +
'</div>' +
'</div>' +
'</div>'
readStatus(myLibrary[i].checked)
}
modalTitle.value = "";
modalAuthor.value = "";
modalPages.value = "";
isRead.checked = false;
}
function readStatus(bookStatus) {
const bookStatusContainer = document.querySelector(".book__read");
if (bookStatus) {
bookStatusContainer.classList.add("yes");
bookStatusContainer.textContent = "I read it";
bookStatusContainer.style.color = "rgb(110, 176, 120)";
} else {
bookStatusContainer.classList.add("no");
bookStatusContainer.textContent = "I have not read it";
bookStatusContainer.style.color = "rgb(194, 89, 89)";
}
}
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#300;400;600&display=swap');
:root {
--light-gray: #dededef3;
--title-color: #333756;
--main-color: #c6c6c6f3;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
font-family: 'Poppins', sans-serif;
background-color: var(--light-gray);
}
header {
text-align: center;
padding-top: 4rem;
color: var(--title-color);
text-transform: uppercase;
letter-spacing: 4px;
}
button {
margin: 1rem;
padding: 0.8rem 2rem;
font-size: 14px;
border-radius: 25px;
background: white;
color: #333756;
font-weight: 600;
border: none;
cursor: pointer;
transition: 0.6s all ease;
}
:focus {
/*outline: 1px solid white;*/
}
button:hover {
background: var(--title-color);
color: white;
}
.add__book:hover,
.cancel:hover {
background: var(--main-color);
color: var(--title-color)
}
.all,
.books__read,
.books__not-read {
border-radius: 0;
text-transform: uppercase;
letter-spacing: 0.1rem;
background: var(--light-gray);
border-bottom: 4px solid var(--title-color)
}
.library__container {
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.book__container {
display: flex;
margin: 2rem 2rem;
}
.modal__container {
display: none;
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
padding-top: 0px;
}
.book,
.modal {
padding: 2rem 2rem;
border-radius: 15px;
background: #333756;
line-height: 3rem;
}
.modal {
position: relative;
width: 50%;
margin: 0 auto;
margin-top: 8rem;
}
.modal__content {
display: flex;
flex-direction: column;
}
label {
color: white;
margin-right: 1rem;
}
input {
padding: 0.5rem;
font-size: 14px;
}
.book__read-elements {
display: flex;
justify-content: space-between;
}
.main,
i {
color: white;
pointer-events: none;
margin: 0.5rem;
}
.book__title,
.book__author,
.book__pages,
.book__read {
color: var(--main-color)
}
.error__message--container {
display: none;
position: fixed;
z-index: 4;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.4);
}
.error__message--modal {
position: relative;
margin: 0 auto;
margin-top: 10rem;
width:40%;
}
.error {
display: flex;
flex-direction: column;
align-items: center;
color: rgb(101, 3, 3);
font-size: 20px;
font-weight: bold;
background: rgb(189, 96, 96);
padding: 3rem 5rem;
border-radius: 10px;
}
.error-btn {
color: rgb(101, 3, 3);
font-weight: bold;
}
.error-btn:hover {
color: white;
background: rgb(101, 3, 3);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css" integrity="sha256-2XFplPlrFClt0bIdPgpz8H7ojnk10H69xRqd9+uTShA=" crossorigin="anonymous" />
<link rel="stylesheet" href="styles.css">
<title>Library</title>
</head>
<body>
<header>
<h1>My Library</h1>
<button class="add">Add New Book</button>
<div class="buttons">
<button class="all">View All</button>
<button class="books__read">Read</button>
<button class="books__not-read">Not Read</button>
</div>
</header>
<div class="error__message--container">
<div class="error__message--modal">
<div class="error">
<p>Complete the form!</p>
<button class ="error-btn">Ok</button>
</div>
</div>
</div>
<!--Modal-->
<form class="modal__container">
<div class="modal">
<div class="modal__content">
<label for="">Title:</label>
<input type="text" id="title">
</div>
<div class="modal__content">
<label for="">Author:</label>
<input type="text" id="author">
</div>
<div class="modal__content">
<label for="">Pages:</label>
<input type="number" id="pages">
</div>
<div>
<label for="read-status">Check the box if you've read this book</label>
<input type="checkbox" id="read-status" value ="check">
</div>
<button class="add__book">Add</button>
<button class="cancel">Cancel</button>
</div>
</form>
<!--End of Modal-->
<div class="library__container"></div>
<script src="script.js"></script>
</body>
</html>
I'm new to OOP and I'm struggling.
I'm building a library where you can add a book with the title, author nr of pages and if you've read it or not. When I add the first book if I check the box it displays that to book is not read(which is false). When I add a new book the read functionality is not applied to that book at all. I have no idea how to fix it
In this function you are checking the status if isRead which is incorrect.
Do this
Call the readStatus function inside the for loop
Pass the current parameter readStatus(myLibrary[i].checked)
Modify readStatus as shown below
function readStatus(status) {
const bookReadStatus = document.querySelector(".book__read");
if (status) {
bookReadStatus.classList.add("yes");
bookReadStatus.textContent = "I read it";
bookReadStatus.style.color = "rgb(110, 176, 120)";
} else {
bookReadStatus.classList.add("no");
bookReadStatus.textContent = "I have not read it";
bookReadStatus.style.color = "rgb(194, 89, 89)";
}
}

Adding a square root function to a calc using js

So, I made a calculator, and I want to add a square root function, but I know there is no already made function that finds the square root of numbers. So what elements can I combine to find the square root of a number?
const screen = document.querySelector("#screen");
const clearButton = document.querySelector("#clear");
const equalsButton = document.querySelector("#equals");
const decimalButton = document.querySelector("#decimal");
let isFloat = false;
let signOn = false;
let firstNumber = "";
let operator = "";
let secondNumber = "";
let result = "";
const allClear = () => {
isFloat = false;
signOn = false;
firstNumber = "";
operator = "";
secondNumber = "";
result = "";
screen.value = "0";
};
const calculate = () => {
if (operator && result === "" && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
secondNumber = screen.value.substring(firstNumber.length + 3);
switch (operator) {
case "+":
result = Number((Number(firstNumber) + Number(secondNumber)).toFixed(3));
break;
case "-":
result = Number((Number(firstNumber) - Number(secondNumber)).toFixed(3));
break;
case "*":
result = Number((Number(firstNumber) * Number(secondNumber)).toFixed(3));
break;
case "/":
result = Number((Number(firstNumber) / Number(secondNumber)).toFixed(3));
break;
default:
}
screen.value = result;
}
};
clear.addEventListener("click", allClear);
document.querySelectorAll(".number").forEach((numberButton) => {
numberButton.addEventListener("click", () => {
if (screen.value === "0") {
screen.value = numberButton.textContent;
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent === "0") {
} else if ([" 0", "+0", "-0"].includes(screen.value.substring(screen.value.length - 2))
&& numberButton.textContent !== "0") {
screen.value = screen.value.substring(0, screen.value.length - 1) + numberButton.textContent;
} else if (result || result === 0) {
allClear();
screen.value = numberButton.textContent;
} else {
screen.value += numberButton.textContent;
}
});
});
decimalButton.addEventListener("click", () => {
if (result || result === 0) {
allClear();
isFloat = true;
screen.value += ".";
} else if (!isFloat) {
isFloat = true;
if ([" ", "+", "-"].includes(screen.value[screen.value.length - 1])) {
screen.value += "0.";
} else {
screen.value += ".";
}
}
});
document.querySelectorAll(".operator").forEach((operatorButton) => {
operatorButton.addEventListener("click", () => {
if (result || result === 0) {
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (operator && ![" ", "+", "-", "."].includes(screen.value[screen.value.length - 1])) {
calculate();
isFloat = false;
signOn = false;
firstNumber = String(result);
operator = operatorButton.dataset.operator;
result = "";
screen.value = `${firstNumber} ${operatorButton.textContent} `;
} else if (!operator) {
isFloat = false;
firstNumber = screen.value;
operator = operatorButton.dataset.operator;
screen.value += ` ${operatorButton.textContent} `;
} else if (!signOn
&& !["*", "/"].includes(operatorButton.dataset.operator)
&& screen.value[screen.value.length - 1] === " ") {
signOn = true;
screen.value += operatorButton.textContent;
}
});
});
equalsButton.addEventListener("click", calculate);
* {
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
font-weight: 300;
margin: 0;
padding: 0;
}
body {
background-color: #222;
height: 100vh;
}
header {
background-color: #333;
padding: 40px 0;
}
header h1 {
-webkit-background-clip: text;
background-clip: text;
background-image: linear-gradient(to right bottom, #fff, #777);
color: transparent;
font-size: 40px;
letter-spacing: 2px;
text-align: center;
text-transform: uppercase;
}
main {
background-color: #222;
display: flex;
justify-content: center;
padding: 60px 0;
}
main #container {
background-color: #333;
box-shadow: 0 5px 5px #111;
padding: 20px;
}
.clearfix:after {
clear: both;
content: " ";
display: block;
font-size: 0;
height: 0;
visibility: hidden;
}
#container .row:not(:last-child) {
margin-bottom: 9px;
}
#container input,
#container button {
float: left;
}
#container input:focus,
#container button:focus {
outline: none;
}
#container input {
background-color: #222;
border: 1px solid #999;
border-right-width: 0;
color: #999;
font-size: 22px;
font-weight: 300;
height: 80px;
padding-right: 14px;
text-align: right;
width: 261px;
}
#container button {
background-color: #222;
border: none;
box-shadow: 0 3px 0 #111;
color: #999;
font-size: 20px;
height: 80px;
margin-right: 7px;
width: 80px;
}
#container button:active {
box-shadow: 0 2px 0 #111;
transform: translateY(1px);
}
#container #clear,
#container .operator,
#container #equals {
color: #111;
}
#container #clear,
#container .operator {
margin-right: 0;
}
#container #clear {
background-color: #e95a4b;
border: 1px solid #999;
border-left-width: 0;
box-shadow: none;
cursor: pointer;
}
#container #clear:active {
box-shadow: none;
transform: none;
}
#container .operator {
background-color: #999;
box-shadow: 0 3px 0 #555;
}
#container .operator:active {
box-shadow: 0 2px 0 #555;
}
#container #equals {
background-color: #2ecc71;
box-shadow: 0 3px 0 #155d34;
}
#container #equals:active {
box-shadow: 0 2px 0 #155d34;
}
#media only screen and (max-width: 400px) {
header {
padding: 28px 0;
}
header h1 {
font-size: 36px;
}
main {
padding: 40px 0;
}
main #container {
padding: 16px;
}
#container .row:not(:last-child) {
margin-bottom: 7px;
}
#container input {
font-size: 18px;
height: 60px;
padding-right: 10px;
width: 195px;
}
#container button {
font-size: 16px;
height: 60px;
margin-right: 5px;
width: 60px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Roboto:300" rel="stylesheet">
<link href="Project 1.css" rel="stylesheet">
</head>
<body>
<header>
<h1>Calculator</h1>
</header>
<main>
<div id="container">
<div class="row clearfix">
<input id="screen" value="0" disabled type="text">
<button id="clear">AC</button>
</div>
<div class="row clearfix">
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button data-operator="+" class="operator">+</button>
</div>
<div class="row clearfix">
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button data-operator="-" class="operator">-</button>
</div>
<div class="row clearfix">
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button data-operator="*" class="operator">×</button>
</div>
<div class="row clearfix">
<button id="decimal">.</button>
<button class="number">0</button>
<button id="equals">=</button>
<button data-operator="/" class="operator">÷</button>
</div>
</div>
</main>
<script src="Project 1.js"></script>
</body>
</html>
This is the code for the calc.. Feel free to edit it and explain to me what you did.
There is already one.
The Math.sqrt() function returns the square root of a number, that is, ∀x≥0,Math.sqrt(x)=x
=the uniquey≥0such thaty2=x
MDN Docs
You can use javascript built in
Math.sqrt(number)

Addition table to modal and catching data from array

I get a problem when I try generate table in modal with data from js code.
There is a problem with 249 line in js. I can not understand why my params.progress array is not defined.
rock-paper-scissors app on codepen
I create new object in empty params.progress array after every player move:
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore+":"+params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
Finally I try to generate table with those data:
function makeTableFromProgress() {
var resultsTableBody = document.querySelector('#resultsTableBody');
var rows = params.progress.length;
for (i = 0; i<rows; i++) {
var row = resultsTableBody.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = params.progress[i]['number'];
cell2.innerHTML = params.progress[i]['playerMove'];
cell3.innerHTML = params.progress[i]['computerMove'];
cell4.innerHTML = params.progress[i]['gameResult'];
}
}
In modal window, like this:
<table>
<thead>
<tr>
<th>No.</th>
<th>Player move</th>
<th>Computer move</th>
<th>Game result</th>
</tr>
</thead>
<tbody id="resultsTableBody"></tbody>
</table>
And it brings kind of that problem:
Cannot read property 'number' of undefined
Thanks for help
The problem is in function makeTableFromProgress. i must start with 1 instead of 0 and also insertRow(i - 1); instead of insertRow(i);
function makeTableFromProgress() {
var resultsTableBody = document.querySelector('#resultsTableBody');
var rows = params.progress.length;
for (i = 1; i < rows; i++) {
var row = resultsTableBody.insertRow(i - 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = params.progress[i]['number'];
cell2.innerHTML = params.progress[i]['playerMove'];
cell3.innerHTML = params.progress[i]['computerMove'];
cell4.innerHTML = params.progress[i]['gameResult'];
}
};
The final code will be this
var userScore_span = document.getElementById("user-score");
var computerScore_span = document.getElementById("computer-score");
var scoreBoard_div = document.querySelector(".score-board");
var result_p = document.querySelector(".result > p");
var moveButtons = document.querySelectorAll("[data-move]");
var newGame_div = document.querySelector(".newGame");
var choices_div = document.querySelector(".choices");
var message_p = document.getElementById("message");
var trophy_p = document.getElementById("numberOfWins");
var roundsCounter_p = document.getElementById("numberOfRounds");
var modal_h = document.getElementById("endMessage");
var userName_div = document.getElementById("user-label");
var userName;
var numberOfGames;
var params = {
userScore: 0,
computerScore: 0,
numberOfRounds: 0,
progress: []
}
function main() {
moveButtons.forEach(function(button) {
var userChoice = button.dataset.move;
button.addEventListener('click', function() {
game(userChoice);
});
});
}
function game(userChoice) {
var computerChoice = getComputerChoice();
switch (userChoice + computerChoice) {
case "RockRock":
case "PaperPaper":
case "ScissorsScissors":
draw(userChoice, computerChoice);
break;
case "RockScissors":
case "PaperRock":
case "ScissorsPaper":
win(userChoice, computerChoice);
break;
case "RockPaper":
case "PaperScissors":
case "ScissorsRock":
lose(userChoice, computerChoice);
break;
}
}
function getComputerChoice() {
var choices = ['Rock', 'Paper', 'Scissors'];
randomNumber = Math.floor(Math.random() * 3)
return choices[randomNumber];
}
function draw(userChoice, computerChoice) {
params.numberOfRounds++;
roundsCounter_p.innerHTML = "Number of rounds: " + params.numberOfRounds;
computerScore_span.innerHTML = params.computerScore;
userScore_span.innerHTML = params.userScore;
var smallerUserWord = "user ".fontsize(4);
var smallerCompWord = " comp".fontsize(4);
result_p.innerHTML = smallerUserWord + userChoice + " vs " + computerChoice + smallerCompWord + "<br>It is a draw!";
document.getElementById(userChoice).classList.add('gray-glow');
setTimeout(function() {
document.getElementById(userChoice).classList.remove('gray-glow')
}, 400);
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore + ":" + params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
}
function win(userChoice, computerChoice) {
params.numberOfRounds++;
roundsCounter_p.innerHTML = "Number of rounds: " + params.numberOfRounds;
params.userScore++;
userScore_span.innerHTML = params.userScore;
computerScore_span.innerHTML = params.computerScore;
var smallerUserWord = "user ".fontsize(4);
var smallerCompWord = " comp".fontsize(4);
result_p.innerHTML = smallerUserWord + userChoice + " vs " + computerChoice + smallerCompWord + "<br>You won!";
document.getElementById(userChoice).classList.add('green-glow');
setTimeout(function() {
document.getElementById(userChoice).classList.remove('green-glow')
}, 400);
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore + ":" + params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
endGame();
}
function lose(userChoice, computerChoice) {
params.numberOfRounds++;
roundsCounter_p.innerHTML = "Number of rounds: " + params.numberOfRounds;
params.computerScore++;
computerScore_span.innerHTML = params.computerScore;
userScore_span.innerHTML = params.userScore;
var smallerUserWord = "user ".fontsize(4);
var smallerCompWord = " comp".fontsize(4);
result_p.innerHTML = smallerUserWord + userChoice + " vs " + computerChoice + smallerCompWord + "<br>You lost!";
document.getElementById(userChoice).classList.add('red-glow');
setTimeout(function() {
document.getElementById(userChoice).classList.remove('red-glow')
}, 400);
var objectResults = {
number: params.numberOfRounds,
playerMove: userChoice,
computerMove: computerChoice,
gameResult: params.userScore + ":" + params.computerScore,
}
params.progress[params.numberOfRounds] = objectResults;
endGame();
}
function newGame() {
newGame_div.addEventListener('click', function() {
howManyWins();
})
main();
}
function howManyWins() {
var userAnswer = prompt("TILL HOW MANY WINS?");
if (userAnswer === null || userAnswer === "" || isNaN(userAnswer)) {
thereIsAnError();
} else {
giveMeYourName();
resetScore();
games(userAnswer);
}
}
function thereIsAnError() {
message_p.innerHTML = "Please press NEW GAME and choose the number!";
setTimeout(function() {
message_p.innerHTML = ""
}, 3000);
}
function giveMeYourName() {
var name = prompt("WHAT IS YOUR NAME?");
if (name === null || name === "" || isNaN(name) === false) {
thereIsAnError();
document.querySelector('#trophy').classList.add('trophydisabled');
} else if (name.length > 9) {
message_p.innerHTML = "Your name is too long. 9 letters summary!";
} else {
document.querySelector('#trophy').classList.remove('trophydisabled');
choices_div.classList.remove('choices-disabled');
newGame_div.classList.add('newGame-disabled');
userName_div.innerHTML = name;
userName = name;
}
}
function resetScore() {
params.userScore = 0;
params.computerScore = 0;
params.numberOfRounds = 0;
userScore_span.innerHTML = params.userScore;
computerScore_span.innerHTML = params.computerScore;
roundsCounter_p.innerHTML = "";
}
function games(userAnswer) {
trophy_p.innerHTML = "Up to: " + userAnswer;
numberOfGames = userAnswer;
}
function endGame() {
if (numberOfGames == params.userScore) {
choices_div.classList.add('choices-disabled');
newGame_div.classList.remove('newGame-disabled');
result_p.innerHTML = "";
userName_h = userName;
modal_h.innerHTML = userName + "<br>You won the ENTIRE game!";
makeTableFromProgress()
showModal();
} else if (numberOfGames == params.computerScore) {
choices_div.classList.add('choices-disabled');
newGame_div.classList.remove('newGame-disabled');
showModal();
result_p.innerHTML = "";
userName_h = userName;
modal_h.innerHTML = userName + "<br>You lose the ENTIRE game!";
makeTableFromProgress()
showModal();
}
}
newGame();
choices_div.classList.add('choices-disabled');
//MODAL
var modal = document.getElementById("modal-one");
var showModal = function() {
event.preventDefault();
document.querySelector('#modal-overlay').classList.add('show');
modal.classList.add('show');
};
var hideModal = function(event) {
event.preventDefault();
document.querySelector('#modal-overlay').classList.remove('show');
this.parentElement.classList.remove('show');
};
var closeButtons = document.querySelectorAll('.close');
for (var i = 0; i < closeButtons.length; i++) {
closeButtons[i].addEventListener('click', hideModal);
}
document.querySelector('#modal-overlay').addEventListener('click', hideModal);
var modals = document.querySelectorAll('.modal');
for (var i = 0; i < modals.length; i++) {
modals[i].addEventListener('click', function(event) {
event.stopPropagation();
});
}
function makeTableFromProgress() {
var resultsTableBody = document.querySelector('#resultsTableBody');
var rows = params.progress.length;
for (i = 1; i < rows; i++) {
var row = resultsTableBody.insertRow(i - 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = params.progress[i]['number'];
cell2.innerHTML = params.progress[i]['playerMove'];
cell3.innerHTML = params.progress[i]['computerMove'];
cell4.innerHTML = params.progress[i]['gameResult'];
}
};
$black: #000;
$white: #fff;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Open Sans', sans-serif;
background-color: #2d3030;
}
header {
background-color: $white;
padding: 20px;
}
header>h1 {
color: #2d3030;
text-align: center;
text-transform: uppercase;
}
#trophy {
margin-top: 20px;
text-align: center;
font-size: 30px;
color: $white;
&.trophydisabled {
display: none;
}
}
#trophy>p {
color: $white;
font-size: 20px;
}
.roundsCounter {
margin-top: 20px;
text-align: center;
}
.roundsCounter>p {
color: $white;
font-size: 20px;
}
.score-board {
margin: 30px auto;
border: 3px solid $white;
border-radius: 5px;
width: 200px;
color: $white;
font-size: 50px;
text-align: center;
padding: 15px 20px;
position: relative;
}
.badge {
width: 100px;
background-color: #af0e0e;
color: $white;
font-size: 15px;
padding: 2px 10px;
text-transform: lowercase;
}
#user-label {
position: absolute;
top: 40px;
left: -110px;
}
#computer-label {
position: absolute;
top: 40px;
right: -110px;
}
.result {
font-size: 40px;
color: $white;
}
.result>p {
text-align: center;
}
.newGame {
margin: 20px auto;
width: 250px;
border: 4px solid $white;
}
.newGame>p {
padding: 10px;
color: $white;
text-align: center;
font-size: 40px;
text-transform: uppercase;
}
.newGame:hover p {
background-color: $white;
color: #d01115;
font-weight: bold;
cursor: pointer;
}
#message {
margin: 20px;
text-align: center;
color: $white;
font-size: 30px;
font-weight: bold;
}
.choices {
margin-top: 30px;
text-align: center;
}
.choices button {
background-color: #2d3030;
display: inline-block;
width: 115px;
border: 4px solid $white;
border-radius: 50%;
font-size: 50px;
color: $white;
padding: 20px;
margin: 10px;
transition: all 0.4s ease;
}
.choices button:hover {
cursor: pointer;
color: #2d3030;
;
background-color: $white;
}
.challenge {
margin-top: 30px;
text-align: center;
color: $white;
font-size: 20px;
font-weight: bold;
}
.gray-glow {
border: 4px solid #787c77;
box-shadow: 0 0 15px 10px #787c77;
}
.green-glow {
border: 4px solid #31b43a;
box-shadow: 0 0 15px 10px #31b43a;
}
.red-glow {
border: 4px solid #d01115;
box-shadow: 0 0 15px 10px #d01115;
}
.choices-disabled {
display: none;
}
.newGame-disabled {
display: none;
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
&.show {
display: block;
}
}
.modal {
display: none;
background: $white;
width: 800px;
position: absolute;
top: 50%;
left: 50%;
transform: translate3d(-50%, -50%, 0);
padding: 20px;
text-align: center;
&.show {
display: block;
}
.close {
font-size: 20px;
position: absolute;
right: 0;
top: 0;
right: 5px;
padding: 5px;
color: $black;
text-decoration: none;
}
table {
text-align: center;
margin: 0 auto;
}
table th {
padding: 20px;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rock Paper Scissors Final</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700,900|Open+Sans:400,700,800&subset=latin-ext" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<header>
<h1>Rock! Paper! Scissors!</h1>
</header>
<div id="trophy">
<i class="fas fa-trophy"></i>
<p id="numberOfWins"></p>
</div>
<div class="roundsCounter">
<p id="numberOfRounds"></p>
</div>
<div class="score-board">
<div id="user-label" class="badge">user</div>
<div id="computer-label" class="badge">comp</div>
<span id="user-score">0</span>:<span id="computer-score">0</span>
</div>
<div class="result">
<p>Rock beats Scissors
<br>Paper covers Rock
<br>Scissors cuts Paper</p>
</div>
<div class="newGame">
<p>New Game</p>
</div>
<p id="message"></p>
<div class="choices">
<button class="player-move" id="Rock" data-move="Rock">
<i class="fas fa-hand-rock"></i>
</button>
<button class="player-move" id="Paper" data-move="Paper">
<i class="fas fa-hand-paper"></i>
</button>
<button class="player-move" id="Scissors" data-move="Scissors">
<i class="fas fa-hand-scissors"></i>
</button>
</div>
<p class="challenge">Let me defeat you!</p>
<div class="overlay" id="modal-overlay">
<div class="modal" id="modal-one">
<i class="fas fa-times"></i>
<h2 id="endMessage">""</h2>
<h3><br>How it was?</h3>
<table>
<thead>
<tr>
<th>No.</th>
<th>Player move</th>
<th>Computer move</th>
<th>Game result</th>
</tr>
</thead>
<tbody id="resultsTableBody"></tbody>
</table>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>

Categories