A issue with the javascript event Object - javascript

I am teaching myself JavaScript and to improve my programming logic I decided to make a Hangman game. Everything works but I am having a problem with the win or lose function. The logic is If the indexCompare array length is === to correctGuesses Array length. Display You win If your lives are === to 0 Display you lose. But for some reason when a correct guess is pushed to the correctGuesses Array if it is a letter that appears more then once in the word. Only 1 occurrence of that letter is added to the array. So certain words never result in a win. And the win condition is never fulfilled. And I think it has something to do with me getting the value from the event Object. I might be wrong though. Any help would be greatly appreciated.
var gameCore = window.onload = function() {
var hangmanWords = ["super", "venus", "spanish", "darkness", "tenebris", "meatball", "human", "omega", "alpha", "isochronism", "supercalifragilisticexpialidocious"];
var commentsArray = ["I belive in you! You can do the thing!", "There is still hope keep trying", "Third times a charm", "You can do this", "Think player think! The counter is almost out", "Never give up", "The last melon 0.0", "What the frog you had one job u_u"];
var hints = ["The opposite of ordinary.", "A planet in are solar system.", "One of the largest languages in the world", "The opposite of light", "A rare word for darkness", "A tasty kind of sphear AKA 'ball' ", "You are A?", "A letter in the greek alphabet.", "Another letter in the greek alphabet.", "A word about time that almost no one uses.", "A big word that you know if you have seen mary poppins but never use."]
var correctGuesses = [];
var lives = 7;
var indexCompare = [];
var choosenWord = []
var arrayCounter = [];
//get elements
var showHint = document.getElementById("hint");
var showLivesLeft = document.getElementById("lives");
var showComments = document.getElementById("comment");
var showLoseOrWin = document.getElementById("winOrLoseDisplay");
// click assigner function
var clickAssigner = function(event) {
var letterHandler = document.getElementsByClassName("letters");
for (var i = 0; i < letterHandler.length; i++) {
letterHandler[i].addEventListener("click", compare, false);
}
var hintHandler = document.getElementById("hint");
hintHandler.addEventListener("click", hint, false);
}
clickAssigner(event);
function hint(event) {
if (arrayCounter[0] === 0) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 1) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 2) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 3) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 4) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 5) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 6) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 7) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 8) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 9) {
showHint.innerHTML = hints[arrayCounter]
};
if (arrayCounter[0] === 10) {
showHint.innerHTML = hints[arrayCounter]
};
}
// word selector and display function
// arrayCounter is the same as i
function wordSelector() {
var randomNumber = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
arrayCounter.push(randomNumber);
var livesContainer = document.createElement("p");
var livesNumber = lives;
showLivesLeft.setAttribute("id", "livesNumbers");
showLivesLeft.appendChild(livesContainer);
livesContainer.innerHTML = livesNumber;
var selectedWord = hangmanWords[arrayCounter];
var wordDisplay = document.getElementById("wordDisplay");
var correctWordDisplay = document.createElement("ul");
var playerGuess;
for (var i = 0; i < selectedWord.length; i++) {
correctWordDisplay.setAttribute("id", "correctWordDisplay-UL");
playerGuess = document.createElement("li");
playerGuess.setAttribute("class", "playerGuess");
playerGuess.innerHTML = "_";
indexCompare.push(playerGuess);
wordDisplay.appendChild(correctWordDisplay);
correctWordDisplay.appendChild(playerGuess);
}
}
wordSelector();
// compare function // decrement lives function // remove health bar
function compare(event) {
var livesDisplay = document.getElementById("livesNumbers");
var btnVal = event.target.value;
var word = hangmanWords[arrayCounter];
for (var i = 0; i < word.length; i++) {
if (word[i] === btnVal) {
indexCompare[i].innerHTML = btnVal;
}
}
var c = word.indexOf(btnVal);
if (c === -1) {
event.target.removeAttribute("letters");
event.target.setAttribute("class", "incorrectLetter");
event.target.removeEventListener("click", compare);
lives -= 1;
livesDisplay.innerHTML = lives;
} else {
event.target.removeAttribute("letters");
event.target.setAttribute("class", "correctLetter");
event.target.removeEventListener("click", compare);
correctGuesses.push(event.target.value);
}
comments();
winOrLose();
// console.log(event);
// console.log(word);
}
// comment function
function comments() {
if (lives === 7) {
showComments.innerHTML = "<p>" + commentsArray[0] + "</p>"
};
if (lives === 6) {
showComments.innerHTML = "<p>" + commentsArray[1] + "</p>"
};
if (lives === 5) {
showComments.innerHTML = "<p>" + commentsArray[2] + "</p>"
};
if (lives === 4) {
showComments.innerHTML = "<p>" + commentsArray[3] + "</p>"
};
if (lives === 3) {
showComments.innerHTML = "<p>" + commentsArray[4] + "</p>"
};
if (lives === 2) {
showComments.innerHTML = "<p>" + commentsArray[5] + "</p>"
};
if (lives === 1) {
showComments.innerHTML = "<p>" + commentsArray[6] + "</p>"
};
if (lives === 0) {
showComments.innerHTML = "<p>" + commentsArray[7] + "</p>"
};
}
// win or lose function
function winOrLose() {
for (var i = 0; i < indexCompare.length; i++) {
if (indexCompare.length === correctGuesses.length) {
showLoseOrWin.innerHTML = "<p>" + "YOU WIN!!! :D" + "</p>";
}
}
if (lives === 0) {
showLoseOrWin.innerHTML = "<p>" + "YOU LOSE u_u" + "</p>";
}
}
function reset() {
}
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html,body,div,span,applet,object,iframe,h1,h2,
h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,
img,ins,kbd,q,
s,samp,small,strike,strong,sub,sup,tt,var,b,u,
i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,
legend,table,caption,tbody,tfoot,thead,tr,th,
td,article,aside,canvas,details,embed,figure,figcaption,
footer,header,hgroup,menu,nav,output,ruby,section,
summary,time,mark,audio,video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section {
display: block;
}
body {
line-height: 1;
}
ol,ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
#container {
overflow: hidden;
max-width: 60%;
background-color: yellowgreen;
margin: 7em auto;
padding: 1em;
}
#wordDisplay {
height: 6em;
background-color: orangered;
margin-bottom: 0.2em;
text-align: center;
padding-top: 2.4em;
font-size: 26px;
display: flex;
justify-content: center;
}
#correctWordDisplay-UL {
list-style: none;
display: flex;
justify-content: center;
}
.playerGuess {
margin: 0em 0.08em;
font-size: 30px;
}
#hint {
max-width: 26em;
padding: 1em;
background-color: skyblue;
border: 0.5em ridge gold;
font-weight: 900;
margin: 0em auto 1em auto;
text-align: center;
}
#hint:hover {
background-color: coral;
cursor: pointer;
font-style: oblique;
}
#letterDiplay {
width: 14em;
float: left;
text-align: center;
background: crimson;
padding: 1em;
}
.letters {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background-color: darkorange;
border: 3px ridge darkblue;
}
.letters:hover {
background: steelblue;
color: white;
cursor: pointer;
}
#theChanceCounter {
text-align: center;
float: right;
width: 14em;
background-color: crimson;
height: 28.9em;
}
/* #lives{
width: 3em;
height: 3em;
margin: 1em auto 0em auto;
background-color: teal;
color: black;
font-weight: 900;
text-align: center;
} */
#livesNumbers {
margin-top: 1em;
border: 3px solid black;
width: 3em;
height: 3em;
padding: 0.9em 0em 0em 0em;
margin: 1em auto 0em auto;
background-color: teal;
color: black;
font-weight: 900;
text-align: center;
}
.correctLetter {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background: green;
color: yellow;
}
.incorrectLetter {
margin: 0.3em auto;
text-align: center;
width: 4em;
height: 3em;
font-weight: 900;
background: red;
color: yellow;
}
#comment {
background-color: forestgreen;
width: 12em;
height: 4em;
padding: 1em 0.4em 0em 0.4em;
margin: 0.3em auto 0.3em auto;
border: 3px solid black;
}
#winOrLoseDisplay {
width: 18em;
padding: 1em;
background-color: skyblue;
border: 0.5em ridge orange;
font-weight: 900;
margin: 0em auto 1em 1.4em;
text-align: center;
float: left;
}
<div id="container">
<section id="wordDisplay">
</section>
<section id="hint">Click for hint.</section>
<section id="letterDiplay">
<button class="letters" value="a">A</button>
<button class="letters" value="b">B</button>
<button class="letters" value="c">C</button>
<button class="letters" value="d">D</button>
<button class="letters" value="e">E</button>
<button class="letters" value="f">F</button>
<button class="letters" value="g">G</button>
<button class="letters" value="h">H</button>
<button class="letters" value="i">I</button>
<button class="letters" value="j">J</button>
<button class="letters" value="k">K</button>
<button class="letters" value="l">L</button>
<button class="letters" value="m">M</button>
<button class="letters" value="n">N</button>
<button class="letters" value="o">O</button>
<button class="letters" value="p">P</button>
<button class="letters" value="q">Q</button>
<button class="letters" value="r">R</button>
<button class="letters" value="s">S</button>
<button class="letters" value="t">T</button>
<button class="letters" value="u">U</button>
<button class="letters" value="v">V</button>
<button class="letters" value="w">W</button>
<button class="letters" value="x">X</button>
<button class="letters" value="y">Y</button>
<button class="letters" value="z">Z</button>
</section>
<section id="winOrLoseDisplay"></section>
<section id="theChanceCounter">
<div id="lives">
</div>
<div id="comment">
</div>
</section>
</div>
</script>

Related

Random questions order when game starts - Trivia javascript game

I have a working code of a 10 text questions' trivia game with a timer (html, javascript, css).
How the questions can be served from a simple .txt file (so I can scale)?
How the javascript can choose the questions in a random order, every time the games starts?
I have studied 1 to get an idea. However, my javascript coding skills are very limited. I would appreciate if you can point me to the right direction.
(function() {
const playButton = document.querySelector("#play");
const letsstartButton = document.querySelector("#lets-start");
const playagainButton = document.querySelector("#play-again");
const howToPlayButton = document.querySelector("#how-to-play-button");
const closeHowToButton = document.querySelector("#close-how-to");
const howToPlayScreen = document.querySelector(".how-to-play-screen");
const mainScreen = document.querySelector(".main-screen");
const triviaScreen = document.querySelector(".trivia-screen");
const resultScreen = document.querySelector(".result-screen");
playButton.addEventListener("click", startTrivia);
letsstartButton.addEventListener("click", startTrivia);
playagainButton.addEventListener("click", startTrivia);
howToPlayButton.addEventListener("click", function() {
howToPlayScreen.classList.remove("hidden");
mainScreen.classList.add("hidden");
});
closeHowToButton.addEventListener("click", function() {
howToPlayScreen.classList.add("hidden");
mainScreen.classList.remove("hidden");
});
const questionLength = 10;
let questionIndex = 0;
let score = 0;
let questions = [];
let timer = null;
function startTrivia() {
//show spinner
questionIndex = 0;
questions = [];
score = 0;
window.setTimeout(function() {
//get questions from server
mainScreen.classList.add("hidden");
howToPlayScreen.classList.add("hidden");
resultScreen.classList.add("hidden");
triviaScreen.classList.remove("hidden");
questions = [{
answers: ["Roma", "Athens", "London", "Japan"],
correct: "Roma",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma1", "Athens1", "London1", "Japan1"],
correct: "Athens1",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma2", "Athens2", "London2", "Japan2"],
correct: "London2",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma3", "Athens3", "London3", "Japan3"],
correct: "London3",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma4", "Athens4", "London4", "Japan4"],
correct: "Athens4",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma5", "Athens5", "London5", "Japan5"],
correct: "Athens5",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma6", "Athens6", "London6", "Japan6"],
correct: "Roma6",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma7", "Athens7", "London7", "Japan7"],
correct: "Japan7",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma8", "Athens8", "London8", "Japan8"],
correct: "London8",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma9", "Athens9", "London9", "Japan9"],
correct: "Japan9",
text: "YOUR TEXT HERE."
}
];
const questionCount = document.getElementById("question-count");
questionCount.innerHTML = questionLength.toString();
displayNextQuestion();
}, 50);
}
const isTriviaCompleted = function() {
return questionLength === questionIndex;
};
function displayNextQuestion() {
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach(function(element) {
element.disabled = false;
element.classList.remove("correct");
element.classList.remove("wrong");
});
if (isTriviaCompleted()) {
showScores();
} else {
startProgressbar();
timer = window.setTimeout(function() {
guess(null);
}, 10000);
setQuizText("This is from");
const textElement = document.getElementById("question-placement");
textElement.innerHTML = questions[questionIndex].text;
const choices = questions[questionIndex].answers;
for (let i = 0; i < choices.length; i++) {
const element = document.getElementById(`answer${i}`);
element.innerHTML = choices[i];
element.addEventListener("click", handleAnswerClick);
}
showProgress();
}
}
function handleAnswerClick(e) {
const el = e.currentTarget;
const answer = el.innerHTML;
el.removeEventListener("click", handleAnswerClick);
guess(answer);
}
function showProgress() {
const questionIndexElement = document.getElementById("question-index");
const index = questionIndex + 1;
questionIndexElement.innerHTML = index.toString();
}
function guess(answer) {
clearTimeout(timer);
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach((element) => {
element.disabled = true;
if (element.innerHTML === questions[questionIndex].correct) {
element.classList.add("correct");
}
});
stopProgressbar();
if (questions[questionIndex].correct === answer) { // correct answer
score++;
setQuizText("Fantastic … Correct!");
} else if (answer) { // incorrect answer
setQuizText("Nice try … You were close.");
answerButtons.forEach((element) => {
if (element.innerHTML === answer) {
element.classList.add("wrong");
}
});
} else {
setQuizText("Your time is out! Oh no!");
}
questionIndex++;
window.setTimeout(function() {
displayNextQuestion();
}, 2500);
}
function setQuizText(text) {
const el = document.getElementById("trivia-text");
el.innerHTML = text;
}
function showScores() {
const scoreElement = document.getElementById("score");
const scoreTotalElement = document.getElementById("score-total");
const scoreNameElement = document.getElementById("score-name");
scoreElement.innerHTML = score.toString();
scoreTotalElement.innerHTML = questionLength.toString();
if (score < 4) {
scoreNameElement.innerHTML = "Newbie";
} else if (score < 7) {
scoreNameElement.innerHTML = "Rookie";
} else if (score < 10) {
scoreNameElement.innerHTML = "Expert";
} else {
scoreNameElement.innerHTML = "Grandmaster";
}
triviaScreen.classList.add("hidden");
resultScreen.classList.remove("hidden");
}
function startProgressbar() {
// select div turn into progressbar
const progressbar = document.getElementById("progress-bar");
progressbar.innerHTML = "";
// create div changes width show progress
const progressbarInner = document.createElement("span");
// Append progressbar to main progressbardiv
progressbar.appendChild(progressbarInner);
// When all set start animation
progressbarInner.style.animationPlayState = "running";
}
function stopProgressbar() {
const progressbar = document.getElementById("progress-bar");
const progressbarInner = progressbar.querySelector("span");
progressbarInner.style.animationPlayState = "paused";
}
}());
*,
*:after,
*:before {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Verdana', cursive;
text-transform: uppercase;
color: #ccc;
letter-spacing: 2px;
}
.container {
background: #999999;
}
.wrapper {
max-width: 800px;
margin: auto;
}
.screen-section {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px 20px 70px;
position: relative;
}
.hidden {
display: none;
}
.trivia-screen-step {
color: #ccc;
}
.trivia-image-wrapper {
max-width: 100%;
margin: 50px auto;
position: relative;
}
.trivia-image {
max-width: 100%;
width: 300px;
position: relative;
z-index: 1;
}
.trivia-timer {
width: 550px;
max-width: 100%;
height: 20px;
border-radius: 3em;
margin-bottom: 50px;
padding: 5px 6px;
}
.trivia-timer span {
display: inline-block;
background: linear-gradient(90deg, #fff, #06c);
height: 10px;
vertical-align: top;
border-radius: 3em;
animation: progressbar-countdown;
animation-duration: 10s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-play-state: paused;
animation-timing-function: linear;
}
#keyframes progressbar-countdown {
0% {
width: 100%;
}
100% {
width: 0%;
}
}
.trivia-question {
margin-bottom: 50px;
}
.how-to-play-screen .default-button {
margin-bottom: 60px;
margin-top: 30px;
}
.button-container {
display: flex;
flex-wrap: wrap;
margin-bottom: 50px;
width: 600px;
max-width: 100%;
}
.button-outer {
flex-basis: 100%;
text-align: center;
margin-bottom: 20px;
max-width: 100%;
}
.default-button {
background: #333333;
border-radius: 3em;
font-family: 'Verdana', cursive;
font-size: 18px;
color: #fff;
letter-spacing: 2.45px;
padding: 10px 8px;
text-transform: uppercase;
transition: background .2s;
outline: none;
width: 250px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.default-button:hover {
background: #222;
}
.default-button[disabled] {
background: transparent;
color: #222;
cursor: default;
}
.default-button[disabled]:hover {
background: transparent;
}
.default-button.correct {
cursor: default;
background: #2bb24a;
color: #fff;
}
.default-button.correct:hover {
background: #2bb24a;
color: #fff;
}
.default-button.wrong {
cursor: default;
background: #F6484C;
color: #fff;
}
.default-button.wrong:hover {
background: #F6484C;
color: #fff;
}
.title {
font-size: 32px;
margin-top: 100px;
}
.text {
line-height: 24px;
font-size: 16px;
font-family: 'Verdana', sans-serif;
text-align: center;
color: #ffffff;
text-transform: none;
}
.trivia-logo {
position: absolute;
bottom: 20px;
}
.trivia-corner-logo {
position: absolute;
left: 0;
top: 15px;
width: 100px;
}
.close-button {
position: absolute;
top: 50px;
right: 0;
background: transparent;
border: none;
color: #fff;
font-family: 'Verdana', cursive;
font-size: 34px;
outline: none;
text-transform: none;
cursor: pointer;
transition: color .2s;
}
.close-button:hover {
color: #eee;
}
.score-name {
margin: 0 0 28px;
font-size: 46px;
}
.score {
font-size: 18px;
margin-bottom: 10px;
}
.description {
text-align: center;
font-family: Verdana, sans-serif;
font-size: 16px;
color: #fff;
text-transform: none;
line-height: 24px;
display: inline-block;
margin-bottom: 30px;
}
#media screen and (min-width: 700px) {
.screen-section {
padding: 50px;
}
<div class="container">
<div class="wrapper">
<div class="screen-section main-screen">
<div class="trivia-image-wrapper">
<img alt="LOGO" src="./assets/Game-Logo.png" class="trivia-image">
</div>
<h1>Trivia</h1>
<div class="button-container">
<div class="button-outer">
<button class="default-button" id="play" type="button">Play</button>
</div>
<div class="button-outer">
<button class="default-button" id="how-to-play-button" type="button">How to play?</button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden how-to-play-screen">
<img alt="LOGO" src="./assets/Game-Logo.png" class="trivia-corner-logo">
<button class="close-button" id="close-how-to" type="button">X</button>
<h2 class="title">How to Play</h2>
<p>Answer questions to score points.</p>
<button class="default-button" id="lets-start" type="button">Ok. Let's start</button>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden trivia-screen">
<div class="trivia-screen-step"><span id="question-index">1</span> out of <span id="question-count">10</span></div>
<div class="trivia-image-wrapper">
<p id="question-placement"></p>
</div>
<div class="trivia-timer" id="progress-bar"></div>
<div class="trivia-question" id="trivia-text"></div>
<div class="button-container" id="answers-container">
<div class="button-outer">
<button class="default-button" id="answer0" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer1" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer2" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer3" type="button"></button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden result-screen">
<div class="trivia-image-wrapper">
<img alt="Trivia LOGO" src="./assets/Game-Logo.png" class="trivia-image">
</div>
<p class="score"><span id="score">0</span> out of <span id="score-total">10</span></p>
<h1 class="score-name" id="score-name">Trivia</h1>
<span class="description">you will learn more.</span>
<button class="default-button" id="play-again" type="button">Play again</button>
<div class="trivia-logo">
<img alt=" logo" src="./assets/-Logo.png">
</div>
</div>
</div>
</div>
In your case the best way would be to create an API (for example https://fastapi.tiangolo.com/) that would return a random question, but if you want to have it in a separate file you would simply have to move the variable questions to another javascript file and import it into the <head> of your web page.
To randomize the JSON you can use the following function:
function shuffleQuestions(questions) {
for (let i = questions.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[questions[i], questions[j]] = [questions[j], questions[i]];
}
}
(function() {
const playButton = document.querySelector("#play");
const letsstartButton = document.querySelector("#lets-start");
const playagainButton = document.querySelector("#play-again");
const howToPlayButton = document.querySelector("#how-to-play-button");
const closeHowToButton = document.querySelector("#close-how-to");
const howToPlayScreen = document.querySelector(".how-to-play-screen");
const mainScreen = document.querySelector(".main-screen");
const triviaScreen = document.querySelector(".trivia-screen");
const resultScreen = document.querySelector(".result-screen");
playButton.addEventListener("click", startTrivia);
letsstartButton.addEventListener("click", startTrivia);
playagainButton.addEventListener("click", startTrivia);
howToPlayButton.addEventListener("click", function() {
howToPlayScreen.classList.remove("hidden");
mainScreen.classList.add("hidden");
});
closeHowToButton.addEventListener("click", function() {
howToPlayScreen.classList.add("hidden");
mainScreen.classList.remove("hidden");
});
const questionLength = 10;
let questionIndex = 0;
let score = 0;
let questions = [];
let timer = null;
function startTrivia() {
//show spinner
questionIndex = 0;
questions = [];
score = 0;
window.setTimeout(function() {
//get questions from server
mainScreen.classList.add("hidden");
howToPlayScreen.classList.add("hidden");
resultScreen.classList.add("hidden");
triviaScreen.classList.remove("hidden");
questions = [{
answers: ["Roma", "Athens", "London", "Japan"],
correct: "Roma",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma1", "Athens1", "London1", "Japan1"],
correct: "Athens1",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma2", "Athens2", "London2", "Japan2"],
correct: "London2",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma3", "Athens3", "London3", "Japan3"],
correct: "London3",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma4", "Athens4", "London4", "Japan4"],
correct: "Athens4",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma5", "Athens5", "London5", "Japan5"],
correct: "Athens5",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma6", "Athens6", "London6", "Japan6"],
correct: "Roma6",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma7", "Athens7", "London7", "Japan7"],
correct: "Japan7",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma8", "Athens8", "London8", "Japan8"],
correct: "London8",
text: "YOUR TEXT HERE."
},
{
answers: ["Roma9", "Athens9", "London9", "Japan9"],
correct: "Japan9",
text: "YOUR TEXT HERE."
}
];
shuffleQuestions(questions);
const questionCount = document.getElementById("question-count");
questionCount.innerHTML = questionLength.toString();
displayNextQuestion();
}, 50);
}
const isTriviaCompleted = function() {
return questionLength === questionIndex;
};
function displayNextQuestion() {
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach(function(element) {
element.disabled = false;
element.classList.remove("correct");
element.classList.remove("wrong");
});
if (isTriviaCompleted()) {
showScores();
} else {
startProgressbar();
timer = window.setTimeout(function() {
guess(null);
}, 10000);
setQuizText("This is from");
const textElement = document.getElementById("question-placement");
textElement.innerHTML = questions[questionIndex].text;
const choices = questions[questionIndex].answers;
for (let i = 0; i < choices.length; i++) {
const element = document.getElementById(`answer${i}`);
element.innerHTML = choices[i];
element.addEventListener("click", handleAnswerClick);
}
showProgress();
}
}
function handleAnswerClick(e) {
const el = e.currentTarget;
const answer = el.innerHTML;
el.removeEventListener("click", handleAnswerClick);
guess(answer);
}
function showProgress() {
const questionIndexElement = document.getElementById("question-index");
const index = questionIndex + 1;
questionIndexElement.innerHTML = index.toString();
}
function guess(answer) {
clearTimeout(timer);
const answersContainer = document.getElementById("answers-container");
const answerButtons = answersContainer.querySelectorAll(".default-button");
answerButtons.forEach((element) => {
element.disabled = true;
if (element.innerHTML === questions[questionIndex].correct) {
element.classList.add("correct");
}
});
stopProgressbar();
if (questions[questionIndex].correct === answer) { // correct answer
score++;
setQuizText("Fantastic … Correct!");
} else if (answer) { // incorrect answer
setQuizText("Nice try … You were close.");
answerButtons.forEach((element) => {
if (element.innerHTML === answer) {
element.classList.add("wrong");
}
});
} else {
setQuizText("Your time is out! Oh no!");
}
questionIndex++;
window.setTimeout(function() {
displayNextQuestion();
}, 2500);
}
function setQuizText(text) {
const el = document.getElementById("trivia-text");
el.innerHTML = text;
}
function showScores() {
const scoreElement = document.getElementById("score");
const scoreTotalElement = document.getElementById("score-total");
const scoreNameElement = document.getElementById("score-name");
scoreElement.innerHTML = score.toString();
scoreTotalElement.innerHTML = questionLength.toString();
if (score < 4) {
scoreNameElement.innerHTML = "Newbie";
} else if (score < 7) {
scoreNameElement.innerHTML = "Rookie";
} else if (score < 10) {
scoreNameElement.innerHTML = "Expert";
} else {
scoreNameElement.innerHTML = "Grandmaster";
}
triviaScreen.classList.add("hidden");
resultScreen.classList.remove("hidden");
}
function startProgressbar() {
// select div turn into progressbar
const progressbar = document.getElementById("progress-bar");
progressbar.innerHTML = "";
// create div changes width show progress
const progressbarInner = document.createElement("span");
// Append progressbar to main progressbardiv
progressbar.appendChild(progressbarInner);
// When all set start animation
progressbarInner.style.animationPlayState = "running";
}
function stopProgressbar() {
const progressbar = document.getElementById("progress-bar");
const progressbarInner = progressbar.querySelector("span");
progressbarInner.style.animationPlayState = "paused";
}
function shuffleQuestions(questions) {
for (let i = questions.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[questions[i], questions[j]] = [questions[j], questions[i]];
}
}
}());
*,
*:after,
*:before {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Verdana', cursive;
text-transform: uppercase;
color: #ccc;
letter-spacing: 2px;
}
.container {
background: #999999;
}
.wrapper {
max-width: 800px;
margin: auto;
}
.screen-section {
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
padding: 20px 20px 70px;
position: relative;
}
.hidden {
display: none;
}
.trivia-screen-step {
color: #ccc;
}
.trivia-image-wrapper {
max-width: 100%;
margin: 50px auto;
position: relative;
}
.trivia-image {
max-width: 100%;
width: 300px;
position: relative;
z-index: 1;
}
.trivia-timer {
width: 550px;
max-width: 100%;
height: 20px;
border-radius: 3em;
margin-bottom: 50px;
padding: 5px 6px;
}
.trivia-timer span {
display: inline-block;
background: linear-gradient(90deg, #fff, #06c);
height: 10px;
vertical-align: top;
border-radius: 3em;
animation: progressbar-countdown;
animation-duration: 10s;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-play-state: paused;
animation-timing-function: linear;
}
#keyframes progressbar-countdown {
0% {
width: 100%;
}
100% {
width: 0%;
}
}
.trivia-question {
margin-bottom: 50px;
}
.how-to-play-screen .default-button {
margin-bottom: 60px;
margin-top: 30px;
}
.button-container {
display: flex;
flex-wrap: wrap;
margin-bottom: 50px;
width: 600px;
max-width: 100%;
}
.button-outer {
flex-basis: 100%;
text-align: center;
margin-bottom: 20px;
max-width: 100%;
}
.default-button {
background: #333333;
border-radius: 3em;
font-family: 'Verdana', cursive;
font-size: 18px;
color: #fff;
letter-spacing: 2.45px;
padding: 10px 8px;
text-transform: uppercase;
transition: background .2s;
outline: none;
width: 250px;
cursor: pointer;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.default-button:hover {
background: #222;
}
.default-button[disabled] {
background: transparent;
color: #222;
cursor: default;
}
.default-button[disabled]:hover {
background: transparent;
}
.default-button.correct {
cursor: default;
background: #2bb24a;
color: #fff;
}
.default-button.correct:hover {
background: #2bb24a;
color: #fff;
}
.default-button.wrong {
cursor: default;
background: #F6484C;
color: #fff;
}
.default-button.wrong:hover {
background: #F6484C;
color: #fff;
}
.title {
font-size: 32px;
margin-top: 100px;
}
.text {
line-height: 24px;
font-size: 16px;
font-family: 'Verdana', sans-serif;
text-align: center;
color: #ffffff;
text-transform: none;
}
.trivia-logo {
position: absolute;
bottom: 20px;
}
.trivia-corner-logo {
position: absolute;
left: 0;
top: 15px;
width: 100px;
}
.close-button {
position: absolute;
top: 50px;
right: 0;
background: transparent;
border: none;
color: #fff;
font-family: 'Verdana', cursive;
font-size: 34px;
outline: none;
text-transform: none;
cursor: pointer;
transition: color .2s;
}
.close-button:hover {
color: #eee;
}
.score-name {
margin: 0 0 28px;
font-size: 46px;
}
.score {
font-size: 18px;
margin-bottom: 10px;
}
.description {
text-align: center;
font-family: Verdana, sans-serif;
font-size: 16px;
color: #fff;
text-transform: none;
line-height: 24px;
display: inline-block;
margin-bottom: 30px;
}
#media screen and (min-width: 700px) {
.screen-section {
padding: 50px;
}
<div class="container">
<div class="wrapper">
<div class="screen-section main-screen">
<div class="trivia-image-wrapper">
<img alt="LOGO" src="./assets/Game-Logo.png" class="trivia-image">
</div>
<h1>Trivia</h1>
<div class="button-container">
<div class="button-outer">
<button class="default-button" id="play" type="button">Play</button>
</div>
<div class="button-outer">
<button class="default-button" id="how-to-play-button" type="button">How to play?</button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden how-to-play-screen">
<img alt="LOGO" src="./assets/Game-Logo.png" class="trivia-corner-logo">
<button class="close-button" id="close-how-to" type="button">X</button>
<h2 class="title">How to Play</h2>
<p>Answer questions to score points.</p>
<button class="default-button" id="lets-start" type="button">Ok. Let's start</button>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden trivia-screen">
<div class="trivia-screen-step"><span id="question-index">1</span> out of <span id="question-count">10</span></div>
<div class="trivia-image-wrapper">
<p id="question-placement"></p>
</div>
<div class="trivia-timer" id="progress-bar"></div>
<div class="trivia-question" id="trivia-text"></div>
<div class="button-container" id="answers-container">
<div class="button-outer">
<button class="default-button" id="answer0" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer1" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer2" type="button"></button>
</div>
<div class="button-outer">
<button class="default-button" id="answer3" type="button"></button>
</div>
</div>
<div class="trivia-logo">
<img alt="logo" src="./assets/-Logo.png">
</div>
</div>
<div class="screen-section hidden result-screen">
<div class="trivia-image-wrapper">
<img alt="Trivia LOGO" src="./assets/Game-Logo.png" class="trivia-image">
</div>
<p class="score"><span id="score">0</span> out of <span id="score-total">10</span></p>
<h1 class="score-name" id="score-name">Trivia</h1>
<span class="description">you will learn more.</span>
<button class="default-button" id="play-again" type="button">Play again</button>
<div class="trivia-logo">
<img alt=" logo" src="./assets/-Logo.png">
</div>
</div>
</div>
</div>

Keep Lines Containing

I am creating a "Keep Lines containing" project. I almost completed this task. But "Search Lines for" is working only 1 line. Multiple "Search
Lines for" is not working. I need "Search Lines for" in multiple lines.
All used HTML, CSS & javascript codes are here
I created a Codepen page for it. Please check : https://codepen.io/coderco/pen/LYGQyqr
function loadfile(fileid, loadid) {
document.getElementById(loadid).value = 'Loading...';
setTimeout(function() {
loadfile2(fileid, loadid)
}, 1000);
}
function loadfile2(fileid, loadid) {
if (!window.FileReader) {
document.getElementById(loadid).value = 'Your browser does not support HTML5 "FileReader" function required to open a file.';
} else {
fileis = document.getElementById(fileid).files[0];
var fileredr = new FileReader();
fileredr.onload = function(fle) {
var filecont = fle.target.result;
document.getElementById(loadid).value = filecont;
}
fileredr.readAsText(fileis);
}
}
function savefile(saveasid, saveid) {
if (!window.Blob) {
alert('Your browser does not support HTML5 "Blob" function required to save a file.');
} else {
var txtwrt = document.getElementById(saveid).value;
if (document.getElementById('dos').checked == true) txtwrt = txtwrt.replace(/\n/g, '\r\n');
var textblob = new Blob([txtwrt], {
type: 'text/plain'
});
var saveas = document.getElementById(saveasid).value;
var dwnlnk = document.createElement('a');
dwnlnk.download = saveas;
dwnlnk.innerHTML = "Download File";
if (window.webkitURL != null) {
dwnlnk.href = window.webkitURL.createObjectURL(textblob);
} else {
dwnlnk.href = window.URL.createObjectURL(textblob);
dwnlnk.onclick = destce;
dwnlnk.style.display = 'none';
document.body.appendChild(dwnlnk);
}
dwnlnk.click();
}
}
function destce(event) {
document.body.removeChild(event.target);
}
function cleartext() {
document.getElementById('input_output').value = '';
document.getElementById('removed').innerHTML = '';
document.getElementById('removed_box').value = '';
}
function SelectAll(id) {
document.getElementById(id).focus();
document.getElementById(id).select();
}
var fieldnum = 0;
var fieldtype = '';
var cacherem = 'no';
var enableregex = 'no';
function makeregexp() {
var regexpoutarr = new Array();
for (var x = 0; x < (fieldnum + 1); x++) {
regexpoutarr[x] = document.getElementById('addfield' + x).value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}
var regexpout = '';
if (fieldtype == 'AND') regexpout = '((?=.*' + regexpoutarr.join(')(?=.*') + ').*)';
if (fieldtype == 'OR') regexpout = '(' + regexpoutarr.join('|') + ')';
if (fieldtype == '') regexpout = document.getElementById('addfield0').value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
return regexpout;
}
function removelines(whatlines) {
var textin = document.getElementById('input_output').value.replace(/\r/g, '');
var toremove = makeregexp();
var textinarr = textin.split('\n');
var textinarrcnt = textinarr.length;
var textoutarr = new Array();
var textoutarrcnt = 0;
var linesremovedcnt = 0;
var casen = 'i';
if (document.getElementById('case_sen').checked == true) casen = '';
if (enableregex == 'yes') toremove = document.getElementById('addfield0').value;
else toremove = makeregexp();
var killfun = 'no';
try {
var toremoveregx = new RegExp(toremove, casen);
} catch (err) {
alert('Something is incorrect (' + err + ') within your regular expression.\nBe sure special characters .*+?^=!:${}()|\\ used as literals have been escaped with a backslash.');
killfun = 'yes';
}
if (killfun == 'no') {
if (whatlines == 'containing' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
if (whatlines == 'notcontaining' && cacherem == 'no') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else linesremovedcnt++;
}
}
var removedcachearr = new Array();
if (whatlines == 'containing' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == false) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
if (whatlines == 'notcontaining' && cacherem == 'yes') {
for (var x = 0; x < textinarrcnt; x++) {
if (toremoveregx.test(textinarr[x]) == true) {
textoutarr[textoutarrcnt] = textinarr[x];
textoutarrcnt++;
} else {
removedcachearr[linesremovedcnt] = textinarr[x];
linesremovedcnt++;
}
}
}
var textout = textoutarr.join('\n');
document.getElementById('input_output').value = textout;
if (cacherem == 'yes') {
var removedcache = removedcachearr.join('\n');
document.getElementById('removed_box').value = removedcache;
}
document.getElementById('removed').innerHTML = '' + linesremovedcnt + ' removed / ' + textoutarrcnt + ' remain.';
}
}
function addfield(field) {
if (field == 'reset') {
document.getElementById('inputfields').innerHTML = '<input type="text" id="addfield0" value="" style="width:100%;" />'
document.getElementById('andbttn').style.display = 'inline-block';
document.getElementById('orbttn').style.display = 'inline-block';
fieldnum = 0;
fieldtype = '';
} else {
fieldnum++;
if (fieldnum == 1) {
if (field == 'andfield') {
document.getElementById('orbttn').style.display = 'none';
fieldtype = 'AND';
} else {
fieldtype = 'OR';
document.getElementById('andbttn').style.display = 'none';
}
}
var newfield = fieldtype + '<input type="text" id="addfield' + fieldnum + '" value="" style="width:100%;" />';
var newdiv = document.createElement('div');
newdiv.innerHTML = newfield;
document.getElementById('inputfields').appendChild(newdiv);
}
resizepage();
}
function disrem() {
var chkedstate = document.getElementById('dremoved').checked;
if (chkedstate == true) {
document.getElementById('removed_box').style.display = 'inline-block';
cacherem = 'yes';
} else {
cacherem = 'no';
document.getElementById('removed_box').value = '';
document.getElementById('removed_box').style.display = 'none';
}
resizepage();
}
function selectele(eleid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(eleid));
range.select();
} else {
var range = document.createRange();
range.selectNode(document.getElementById(eleid));
window.getSelection().addRange(range);
}
}
function regexsrch() {
var chkedstate = document.getElementById('regex_srch').checked;
if (chkedstate == true) {
addfield('reset');
enableregex = 'yes';
document.getElementById('addfielddiv').innerHTML =
'<div style="padding:3px 0px 3px 0px;"><input type="checkbox" id="regex_srch" onclick="regexsrch();" CHECKED />Enable regular expression search. ' +
'Use <span id="catordog" style="color:#990000;" onclick="selectele(this.id)">(cat|dog|bird)</span> for cat OR dog OR bird. Use <span id="catanddog" style="color:#990000;" onclick="selectele(this.id)">((?=.*cat)(?=.*dog)(?=.*bird).*)</span> for cat AND dog AND bird. ' +
'Remember to escape special characters .*+?^=!:${}()|\\ with a backslash when used as literals within a regular expression. Use the <a target="_blank" href="" style="color:#0000FF;">Escape Literal Characters</a> tool. ' +
'Learn more about regular expressions visit <a rel="nofollow" target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" style="color:#0000FF;">developer.mozilla.org</a>.</div>';
} else {
document.getElementById('addfield0').value = '';
enableregex = 'no';
document.getElementById('addfielddiv').innerHTML =
'Add <input type="button" id="andbttn" value="AND" onClick="addfield(\'andfield\');" /> ' +
'<input type="button" id="orbttn" value="OR" onClick="addfield(\'orfield\');" /> search field. ' +
'<input type="button" value="Reset" onClick="addfield(\'reset\');" /> ' +
'<input type="checkbox" id="regex_srch" onclick="regexsrch();" />Enable regular expression search.';
}
resizepage();
}
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
padding: 0px;
font-family: arial;
font-size: 16px;
line-height: 1.7;
}
h1 {
display: block;
font-size: 18px;
font-weight: bold;
margin: 0px;
padding: 0px;
}
.se-for {
font-size: 27px;
font-weight: bold;
color: #b93207;
padding-top: 54px;
}
.contentt,
.wordd {
display: block;
margin: 0px;
padding: 8px 10px 8px 10px;
overflow: scroll;
font-family: arial;
font-size: 16px;
line-height: 1.7;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
border-radius: 4px 4px 4px 4px;
width: 100%;
font-size: 18px;
}
.contentt {
height: 400px;
overflow: auto;
}
.wordd {
height: 99px;
overflow: auto;
}
input {
display: inline-block;
height: 33px;
line-height: 1;
vertical-align: middle;
font-size: 16px;
outline: none;
resize: none;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input::-moz-focus-inner {
border: 0;
padding: 0
}
input[type='radio'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='checkbox'] {
width: 20px;
height: 20px;
vertical-align: middle;
margin: 0px;
padding: 0px;
font-size: 16px;
}
input[type='text'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
color: #000000;
background-color: #FFFFFF;
border: 1px solid #000000;
border-radius: 12px;
}
input[type='button'] {
width: auto;
margin: 3px 0px 3px 0px;
padding: 0px 10px 0px 10px;
font-family: arial;
font-weight: bold;
color: #000000;
border: 1px solid #000000;
background-color: #FFFFFF;
cursor: pointer;
border-radius: 5px;
background: #b93207;
color: #fff;
border: #b93207;
}
input[type='button']:hover {
color: #f9f900;
}
input[type='button']:hover {}
input[type='file'] {
width: 92px;
border-radius: 12px;
overflow: hidden;
padding: 0px;
margin: 0px 0px 0px -92px;
-moz-opacity: 0;
opacity: 0;
cursor: pointer;
}
input[type='file']::-webkit-file-upload-button {
cursor: pointer;
}
div {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
table {
border-collapse: collapse;
}
table,
td {
padding: 0px;
}
.buttonz {
width: 100%;
display: inline-block;
}
#menu {
position: absolute;
z-index: -1;
left: 0px;
top: 0px;
width: 0px;
height: 0%;
margin: 0px;
overflow: auto;
background-color: #E1E1D2;
border-right: 1px solid #000000;
}
div.navcat {
padding: 10px 0px 5px 12px;
font-size: 18px;
font-weight: bold;
font-style: italic;
}
div.navdiv {
height: 2px;
padding: 0px;
margin: 18px 10px 13px 10px;
background-color: #000000;
}
a.nav {
display: inline-block;
padding: 0px;
margin: 10px 0px 10px 10px;
text-decoration: underline;
color: #000000;
}
#toolpadding {
padding: 10px 10px 10px 10px;
}
#tool {
width: 1100px;
margin: 0px;
padding: 0px;
background-color: #fff;
margin: 0 auto;
}
<div id="tool">
<div id="toolpadding">
<div id="topdiv">
<div class="se-for">Search lines for:</div>
<div id="inputfields" style="padding-top:4px;">
<textarea type="text" id="addfield0" class="wordd">Three</textarea>
</div>
<div class="buttonz">
<input type="button" value="Keep Lines Containing" onClick="if(document.getElementById('addfield0').value!='') {removelines('notcontaining');}" />
<input type="checkbox" id="case_sen" />Case sensitive.
</div>
</div>
<div id="middiv" style="height:120px;">
<textarea id="input_output" class="contentt" wrap="off">
One One One One One One One One One One One One One One One
Three Three Three Three Three Three Three Three Three Three
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Two Two Two Two Two Two Two Two Two Two Two Two Two Two Two
Three Three Three Three Three Three Three Three Three Three
Three Three Three Three Three Three Three Three Three Three
Four Four Four Four Four Four Four Four Four Four Four Four
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
Five Five Five Five Five Five Five Five Five Five Five Five
Three Three Three Three Three Three Three Three Three Three
</textarea>
</div>
<div id="btmdiv">
<textarea id="removed_box" rows="4" style="display:none; width:100%; margin-top:10px;" wrap="off">
Removed Line Box - Removed/extracted lines will display here.</textarea>
</div>
</div>
</div>

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)

Javascript - NaN.undefined as textholder problem

I have got a problem at the coding project I am doing, as I formatted the numbers to be shown nicer, I ran into a problem. The webpage when it loads shows NaN. undefined in the total income/expenses at the top. I can't figure out what is the problem.
//Budget controller
var budgetController = (function() {
var Expense = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
this.percentage = -1;
};
Expense.prototype.calcPercentage = function(totalIncome) {
if (totalIncome > 0) {
this.percentage = Math.round((this.value / totalIncome) * 100);
} else {
this.percentage = -1;
}
};
Expense.prototype.getPercentage = function() {
return this.percentage;
};
var Income = function(id, description, value) {
this.id = id;
this.description = description;
this.value = value;
};
var calculateTotal = function(type) {
var sum = 0;
data.allItems[type].forEach(function(cur) {
sum = sum + cur.value;
});
data.totals[type] = sum;
};
var data = {
allItems: {
exp: [],
inc: []
},
totals: {
exp: 0,
inc: 0
},
budget: 0,
percentage: -1
};
return {
addItem: function(type, des, val) {
var newItem, ID;
//create new iD
if (data.allItems[type].length > 0) {
ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
} else {
ID = 0;
}
//CREATe new item, if it is inc or exp
if (type === 'exp') {
newItem = new Expense(ID, des, val);
} else if (type === 'inc') {
newItem = new Income(ID, des, val);
}
// Push all items into data structure and return the new element
data.allItems[type].push(newItem);
return newItem;
},
deleteItem: function(type, id) {
var ids, index;
ids = data.allItems[type].map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.allItems[type].splice(index, 1);
}
},
calculateBudget: function() {
// calculate the total income and expenses
calculateTotal('exp');
calculateTotal('inc');
// calculate the budget: income - expenses
data.budget = data.totals.inc - data.totals.exp;
if (data.totals.inc > 0) {
data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100);
} else {
data.percentage = -1;
}
},
calculatePercentages: function() {
data.allItems.exp.forEach(function(cur) {
cur.calcPercentage(data.totals.inc);
});
},
getPercentages: function() {
var allPerc = data.allItems.exp.map(function(cur) {
return cur.getPercentage();
});
return allPerc;
},
getBudget: function() {
return {
budget: data.budget,
totalInc: data.totals.inc,
totalExp: data.totals.exp,
percentage: data.percentage
};
}
};
})();
// UI Controller
var UIController = (function() {
var DOMstrings = {
inputType: '.add__type',
inputDescription: '.add__description',
inputValue: '.add__value',
inputBtn: '.add__btn',
incomeContainer: '.income__list',
expensesContainer: '.expenses__list',
budgetLabel: '.budget__value',
incomeLabel: '.budget__income--value',
expensesLabel: '.budget__expenses--value',
percentageLabel: '.budget__expenses--percentage',
container: '.container',
expensesPercLabel: '.item__percentage',
dateLabel: '.budget__title--month'
};
var formatNumber = function(num, type) {
var numSplit, int, dec, type;
/* + or - befofe a number
on 2 decimals
comma seperating thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};
var nodeListForEach = function(list, callback) {
for (var i = 0; i < list.length; i++) {
callback(list[i], i);
}
};
return {
getInput: function() {
return {
type: document.querySelector(DOMstrings.inputType).value, //will be either inc or exp
description: document.querySelector(DOMstrings.inputDescription).value,
value: parseFloat(document.querySelector(DOMstrings.inputValue).value)
};
},
addListItem: function(obj, type) {
var html, newHtml, element;
// Create HTML string with placeholder text
if (type === 'inc') {
element = DOMstrings.incomeContainer;
html = '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
} else if (type === 'exp') {
element = DOMstrings.expensesContainer;
html = '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
}
// Replace the placeholder text with some actual data
newHtml = html.replace('%id%', obj.id);
newHtml = newHtml.replace('%description%', obj.description);
newHtml = newHtml.replace('%value%', formatNumber(obj.value, type));
// Insert the HTML into the DOM
document.querySelector(element).insertAdjacentHTML('beforeend', newHtml);
},
deleteListItem: function(selectorID) {
var el = document.getElementById(selectorID);
el.parentNode.removeChild(el);
},
clearFields: function() {
var fields, fieldsArr;
fields = document.querySelectorAll(
DOMstrings.inputDescription + ',' + DOMstrings.inputValue
);
fieldsArr = Array.prototype.slice.call(fields);
fieldsArr.forEach(function(current, index, array) {
current.value = "";
});
fieldsArr[0].focus();
},
displayBudget: function(obj) {
var type;
obj.budget > 0 ? type = 'inc' : type = 'exp';
document.querySelector(DOMstrings.budgetLabel).textContent = formatNumber(obj.budget, type);
document.querySelector(DOMstrings.incomeLabel).textContent = formatNumber(obj.totalInc, 'inc');
document.querySelector(DOMstrings.expensesLabel).textContent = formatNumber(obj.totalExp, 'exp');
if (obj.percentage > 0) {
document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + '%';
} else {
document.querySelector(DOMstrings.percentageLabel).textContent = '---';
}
},
displayPercentages: function(percentages) {
var fields = document.querySelectorAll(DOMstrings.expensesPercLabel);
nodeListForEach(fields, function(current, index) {
if (percentages[index] > 0) {
current.textContent = percentages[index] + '%';
} else {
current.textContent = '---';
}
});
},
getDOMstrings: function() {
return DOMstrings;
}
};
})();
// App Controller - global
var controller = (function(budgetCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.inputBtn).addEventListener('click', ctrlAddItem);
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
document.querySelector(DOM.container).addEventListener('click', ctrlDeleteItem);
};
var updateBudget = function() {
// 1. Calculate the budget
budgetCtrl.calculateBudget();
// 2. Return the budget
var budget = budgetCtrl.getBudget();
// 3. Display the budget on the UI
UICtrl.displayBudget(budget);
};
var updatePercentages = function() {
// 1. Calculate percentages
budgetCtrl.calculatePercentages();
// 2. Read percentages from the budget controller
var percentages = budgetCtrl.getPercentages();
// 3. Update the UI with the new percentages
UICtrl.displayPercentages(percentages);
};
var ctrlAddItem = function() {
var input, newItem;
// 1. Get the field input data
input = UICtrl.getInput();
if (input.description !== "" && !isNaN(input.value) && input.value > 0) {
// 2. Add the item to the budget controller
newItem = budgetCtrl.addItem(input.type, input.description, input.value);
// 3. Add the item to the UI
UICtrl.addListItem(newItem, input.type);
// 4. Clear the fields
UICtrl.clearFields();
// 5. Calculate and update budget
updateBudget();
// 6. Calculate and update percentages
updatePercentages();
}
};
var ctrlDeleteItem = function(event) {
var itemID, splitID, type, ID;
itemID = event.target.parentNode.parentNode.parentNode.parentNode.id;
if (itemID) {
//inc-1
splitID = itemID.split('-');
type = splitID[0];
ID = parseInt(splitID[1]);
// 1. delete the item from the data structure
budgetCtrl.deleteItem(type, ID);
// 2. Delete the item from the UI
UICtrl.deleteListItem(itemID);
// 3. Update and show the new budget
updateBudget();
// 4. Calculate and update percentages
updatePercentages();
}
};
return {
init: function() {
console.log('App has started');
UICtrl.displayBudget({
budget: 0,
totalIncome: 0,
totalExpenses: 0,
percentage: -1
});
setupEventListeners();
}
};
})(budgetController, UIController);
controller.init();
/**********************************************
*** GENERAL
**********************************************/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
color: #555;
font-family: Open Sans;
font-size: 16px;
position: relative;
height: 100vh;
font-weight: 400;
}
.right {
float: right;
}
.red {
color: #FF5049 !important;
}
.red-focus:focus {
border: 1px solid #FF5049 !important;
}
/**********************************************
*** TOP PART
**********************************************/
.top {
height: 40vh;
background-image: linear-gradient(rgba(0, 0, 0, 0.35), rgba(0, 0, 0, 0.35)), url(back.png);
background-size: cover;
background-position: center;
position: relative;
}
.budget {
position: absolute;
width: 350px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
}
.budget__title {
font-size: 18px;
text-align: center;
margin-bottom: 10px;
font-weight: 300;
}
.budget__value {
font-weight: 300;
font-size: 46px;
text-align: center;
margin-bottom: 25px;
letter-spacing: 2px;
}
.budget__income,
.budget__expenses {
padding: 12px;
text-transform: uppercase;
}
.budget__income {
margin-bottom: 10px;
background-color: #28B9B5;
}
.budget__expenses {
background-color: #FF5049;
}
.budget__income--text,
.budget__expenses--text {
float: left;
font-size: 13px;
color: #444;
margin-top: 2px;
}
.budget__income--value,
.budget__expenses--value {
letter-spacing: 1px;
float: left;
}
.budget__income--percentage,
.budget__expenses--percentage {
float: left;
width: 34px;
font-size: 11px;
padding: 3px 0;
margin-left: 10px;
}
.budget__expenses--percentage {
background-color: rgba(255, 255, 255, 0.2);
text-align: center;
border-radius: 3px;
}
/**********************************************
*** BOTTOM PART
**********************************************/
/***** FORM *****/
.add {
padding: 14px;
border-bottom: 1px solid #e7e7e7;
background-color: #f7f7f7;
}
.add__container {
margin: 0 auto;
text-align: center;
}
.add__type {
width: 55px;
border: 1px solid #e7e7e7;
height: 44px;
font-size: 18px;
color: inherit;
background-color: #fff;
margin-right: 10px;
font-weight: 300;
transition: border 0.3s;
}
.add__description,
.add__value {
border: 1px solid #e7e7e7;
background-color: #fff;
color: inherit;
font-family: inherit;
font-size: 14px;
padding: 12px 15px;
margin-right: 10px;
border-radius: 5px;
transition: border 0.3s;
}
.add__description {
width: 400px;
}
.add__value {
width: 100px;
}
.add__btn {
font-size: 35px;
background: none;
border: none;
color: #28B9B5;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1.1;
margin-left: 10px;
}
.add__btn:active {
transform: translateY(2px);
}
.add__type:focus,
.add__description:focus,
.add__value:focus {
outline: none;
border: 1px solid #28B9B5;
}
.add__btn:focus {
outline: none;
}
/***** LISTS *****/
.container {
width: 1000px;
margin: 60px auto;
}
.income {
float: left;
width: 475px;
margin-right: 50px;
}
.expenses {
float: left;
width: 475px;
}
h2 {
text-transform: uppercase;
font-size: 18px;
font-weight: 400;
margin-bottom: 15px;
}
.icome__title {
color: #28B9B5;
}
.expenses__title {
color: #FF5049;
}
.item {
padding: 13px;
border-bottom: 1px solid #e7e7e7;
}
.item:first-child {
border-top: 1px solid #e7e7e7;
}
.item:nth-child(even) {
background-color: #f7f7f7;
}
.item__description {
float: left;
}
.item__value {
float: left;
transition: transform 0.3s;
}
.item__percentage {
float: left;
margin-left: 20px;
transition: transform 0.3s;
font-size: 11px;
background-color: #FFDAD9;
padding: 3px;
border-radius: 3px;
width: 32px;
text-align: center;
}
.income .item__value,
.income .item__delete--btn {
color: #28B9B5;
}
.expenses .item__value,
.expenses .item__percentage,
.expenses .item__delete--btn {
color: #FF5049;
}
.item__delete {
float: left;
}
.item__delete--btn {
font-size: 22px;
background: none;
border: none;
cursor: pointer;
display: inline-block;
vertical-align: middle;
line-height: 1;
display: none;
}
.item__delete--btn:focus {
outline: none;
}
.item__delete--btn:active {
transform: translateY(2px);
}
.item:hover .item__delete--btn {
display: block;
}
.item:hover .item__value {
transform: translateX(-20px);
}
.item:hover .item__percentage {
transform: translateX(-20px);
}
.unpaid {
background-color: #FFDAD9 !important;
cursor: pointer;
color: #FF5049;
}
.unpaid .item__percentage {
box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
}
.unpaid:hover .item__description {
font-weight: 900;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:100,300,400,600" rel="stylesheet" type="text/css">
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css">
<link type="text/css" rel="stylesheet" href="style.css">
<title>Budgety</title>
</head>
<body>
<div class="top">
<div class="budget">
<div class="budget__title">
Available Budget in <span class="budget__title--month">%Month%</span>:
</div>
<div class="budget__value">+ 2,345.64</div>
<div class="budget__income clearfix">
<div class="budget__income--text">Income</div>
<div class="right">
<div class="budget__income--value">+ 4,300.00</div>
<div class="budget__income--percentage"> </div>
</div>
</div>
<div class="budget__expenses clearfix">
<div class="budget__expenses--text">Expenses</div>
<div class="right clearfix">
<div class="budget__expenses--value">- 1,954.36</div>
<div class="budget__expenses--percentage">45%</div>
</div>
</div>
</div>
</div>
<div class="bottom">
<div class="add">
<div class="add__container">
<select class="add__type">
<option value="inc" selected>+</option>
<option value="exp">-</option>
</select>
<input type="text" class="add__description" placeholder="Add description">
<input type="number" class="add__value" placeholder="Value">
<button class="add__btn"><i class="ion-ios-checkmark-outline"></i></button>
</div>
</div>
<div class="container clearfix">
<div class="income">
<h2 class="icome__title">Income</h2>
<div class="income__list">
<!--
<div class="item clearfix" id="income-0">
<div class="item__description">Salary</div>
<div class="right clearfix">
<div class="item__value">+ 2,100.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="income-1">
<div class="item__description">Sold car</div>
<div class="right clearfix">
<div class="item__value">+ 1,500.00</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
<div class="expenses">
<h2 class="expenses__title">Expenses</h2>
<div class="expenses__list">
<!--
<div class="item clearfix" id="expense-0">
<div class="item__description">Apartment rent</div>
<div class="right clearfix">
<div class="item__value">- 900.00</div>
<div class="item__percentage">21%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
<div class="item clearfix" id="expense-1">
<div class="item__description">Grocery shopping</div>
<div class="right clearfix">
<div class="item__value">- 435.28</div>
<div class="item__percentage">10%</div>
<div class="item__delete">
<button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button>
</div>
</div>
</div>
-->
</div>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
The problem is that in the function formatNumber, the value num is not initialized at first time. For solving this, you can put a default value when the value of num is empty, like this:
var formatNumber = function(num = 0, type = '') {
var numSplit, int, dec, type;
/* + or - befofe a number
on 2 decimals
comma seperating thousands
*/
num = Math.abs(num);
num = num.toFixed(2);
numSplit = num.split('.');
int = numSplit[0];
if (int.length > 3) {
int = int.substr(0, int.length - 3) + ',' + int.substr(int.length - 3, 3); //input 23510, output 23,510
}
dec = numSplit[1];
return (type === 'exp' ? '-' : '+') + ' ' + int + '.' + dec;
};

Why can't I add a count to my onclick function?

I wanted to try using a count to change the behavior of a click. All my other conditions worked but I don't understand why my count condition doesn't. Does anyone know what I can do to make it work?
For the count I tried -- (this.count == 2), (count == 2), and (uh.count == 2)
function uh() {
var words;
var conf = confirm("ooh that felt goood");
var button = document.querySelector("#selector");
var box =
document.querySelector("#box");
var count = 0;
if (this.count == 5) {
button.classname = "button3";
words = " ";
} else if (this.count == 4) {
button.classname = "button3";
words = "I give up. This is all you get.";
count++;
} else if (this.count == 3) {
button.classname = "button3";
words = "...";
count++;
} else if (this.count == 2) {
button.className = "button2";
words = "the power?";
count++;
} else if (button.className == "button3") {
button.className = "button2";
words = "ahahaha... ha.. uh..";
count++;
} else if (button.className == "button2") {
button.className = "button3";
box.className = "box";
words = "THE POWER";
} else if (conf == true) {
words = "AHAHAHA I HAVE YOU NOW";
button.className = "button2";
} else {
words = "...";
button.className = "button";
}
document.querySelector(".header").innerHTML = words;
}
body {
background-color: black;
}
#header {
text-align: center;
}
.header {
background-color: #000099;
color: white;
display: inline-block;
border: 5px solid white;
padding: 20px;
width: 90%;
}
#box {
text-align: center;
background-color: green;
height: 500px;
}
.box {
text-align: center;
height: 500px;
}
.button {
background-color: grey;
color: white;
margin: 170px;
text-decoration: none;
display: inline-block;
font-size: 20px;
}
.button2 {
background-color: #ff0000;
border: none;
color: white;
padding: 15px 32px;
margin: 170px;
text-decoration: none;
display: inline-block;
font-size: 40px;
box-shadow: 0px 0px 10px white;
}
.button3 {
background-color: black;
border: none;
color: red;
padding: 30px 60px;
margin: 170px;
text-decoration: none;
display: inline-block;
font-size: 60px;
box-shadow: 0px 0px 20px 5px gold;
}
<div id=h eader>
<h1 class="header"> I feel an itch...
<h1>
</div>
<div id="box">
<input type="button" id="selector" class="button" value="CLICK ME" onclick="uh()">
</div>
count is declared and initialized anew each time uh() is called. The variable lifetime ends when the function ends so there is no way to preserve its value across multiple calls to uh().
What you could do, is declare an object called count with a same name property and call() uh on the object. Then this will refer to the object uh() gets called on and thus this.count will have a transferable value across multiple calls on the same object.
var count = {count: 0};
console.log(count.count);//0
up.call(count);
function up() {
this.count++;
//... here add any kind of check on the value of count
}
console.log(count.count);//1

Categories