My Dollars Per Second Counter Isn't Working. I have the right id in document.querySelector and the calculations are right. The Dollars per Second just isn't updating It seems the function is not running properly. I don't know what to do at all. I'm not getting any errors in the console either.
Click This Image
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#beta/dist/js.cookie.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>Computer Clicker</title>
</head>
<body onload="updateDollars()">
<div class="counterclass">
<h1 id="counter">0 dollars</h1>
<h3 id="dps">0.0 dps(Dollars per Second)</h3>
</div>
<div class="clickme">
<img
id="slightlydamagedcomputer"
onclick="clicker.dollars += clicker.clickMultiplier; var click = document.querySelector('.clickme'); click.style.animation = 'click 0.2s'; var clone = click.cloneNode(true); click.parentNode.replaceChild(clone, click);"
src="slightlydamagedcomputer.png"
alt="Drawing of a Smoking Computer"
width="500"
height="500"
/>
</div>
<div class="upgradesleft">
<h1>Upgrades</h1>
<div class="upgradeoptions">
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
</div>
</div>
<div class="genright">
<h1>Generators</h1>
<div class="genoptions"></div>
</div>
</body>
</html>
Javascript:
dollars: 0,
clickMultiplier: 1,
generators: {
cardboardMouse: {
amount: 0,
cost: 10,
dps: 0.5,
dollarsToShow: 5,
dollarsToUnlock: 10,
name: "Cardboard Mouse",
description:
"A poorly crafted cardboard version of a mouse. Need I say more?",
},
cardboardKeyboard: {
amount: 0,
cost: 50,
dps: 1,
dollarsToShow: 25,
dollarsToUnlock: 50,
name: "Cardboard Keyboard",
description:
"A poorly crafted cardboard version of a keyboard. Makes a satisfying noise.",
},
},
};
var delay = 0;
function thingClicked(thing) {
if (clicker.generators[thing].cost <= clicker.dollars) {
clicker.dollars -= clicker.generators[thing].cost;
clicker.generators[thing].amount++;
clicker.generators[thing].cost += Math.round(
clicker.generators[thing].cost * 0.15
);
updateGenerators();
/*updateDollarsPerSecond();*/
}
}
function dummyFunction() {
updateDollarsPerSecond();
}
function updateDollarsPerSecond(){
for (i in clicker.generators) {
dummyFunction();
console.log((clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)")
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
}
}
function updateGenerators() {
document.querySelector(".genoptions").innerHTML = "";
for (i in clicker.generators) {
document.querySelector(
".genoptions"
).innerHTML += `<div><button onclick="thingClicked('${i}');"><h3>${clicker.generators[i].name}(${clicker.generators[i].amount})</h3><p>${clicker.generators[i].description}</p><p class="cost">$${clicker.generators[i].cost}</p><p class="dps">${clicker.generators[i].dps} dps</p></button></div>`;
}
}
function updateDollars() {
if (Cookies.get("clicker") != null && Cookies.get("clicker") != "undefined") {
var clicker1 = JSON.parse(Cookies.get("clicker"));
for (i in clicker.generators) {
if (clicker1.generators[i] == null) {
clicker1.generators[i] = clicker.generators[i];
}
}
clicker = clicker1;
}
updateGenerators();
setInterval(() => {
for (i in clicker.generators) {
clicker.dollars +=
(clicker.generators[i].amount * clicker.generators[i].dps) / 100;
}
if (clicker.dollars != 1) {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollars";
} else {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollar";
}
delay++;
if (delay >= 40) {
Cookies.set("clicker", JSON.stringify(clicker), { expires: 100000 });
delay = 0;
}
}, 10);
}
CSS:
#keyframes click {
50% {
transform: scale(0.95);
}
100% {
transform: scale(1);
}
}
body {
background-color: aquamarine;
}
h1,
#dps {
font-family: "Joan", serif;
}
#dps {
font-size: 15px;
}
#counter,
#dps {
text-align: center;
margin: 0px;
margin-top: 21.44px;
}
#slightlydamagedcomputer {
display: block;
margin: auto;
}
#slightlydamagedcomputer:hover {
cursor: pointer;
}
.upgradesleft {
left: 0px;
}
.genright {
right: 0px;
}
.upgradesleft,
.genright {
position: absolute;
top: 0px;
height: 100%;
}
.upgradesleft h1,
.genright h1 {
text-align: center;
}
.upgradeoptions button,
.genoptions button {
background-color: aliceblue;
border-style: solid;
border-color: black;
border-width: 1px;
height: 100px;
width: 400px;
display: block;
}
.upgradeoptions button {
border-radius: 0px 15px 15px 0px;
/*display: none;*/
}
.genoptions button {
border-radius: 15px 0px 0px 15px;
/*display: none;*/
}
.upgradeoptions div,
.genoptions div {
position: relative;
}
.cost {
left: 0px;
top: 0px;
border-radius: 15px;
}
.dps {
right: 0px;
top: 0px;
border-radius: 0px 0px 0px 15px;
}
.cost,
.dps {
background-color: lightgray;
border-style: solid;
border-color: black;
border-width: 1px;
position: absolute;
margin: 0px;
padding: 5px;
}
You are not updating the element with id dps. So you need to update it.
You need to modify your updateGenerators() function by adding the following lines:
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
and the updateGenerators() function will be:
function updateGenerators() {
document.querySelector(".genoptions").innerHTML = "";
for (i in clicker.generators) {
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
document.querySelector(
".genoptions"
).innerHTML += `<div><button onclick="thingClicked('${i}');"><h3>${clicker.generators[i].name}(${clicker.generators[i].amount})</h3><p>${clicker.generators[i].description}</p><p class="cost">$${clicker.generators[i].cost}</p><p class="dps">${clicker.generators[i].dps} dps</p></button></div>`;
}
}
Check the following modified js code:
var clicker = {
dollars: 0,
clickMultiplier: 1,
generators: {
cardboardMouse: {
amount: 0,
cost: 10,
dps: 0.5,
dollarsToShow: 5,
dollarsToUnlock: 10,
name: "Cardboard Mouse",
description: "A poorly crafted cardboard version of a mouse. Need I say more?",
},
cardboardKeyboard: {
amount: 0,
cost: 50,
dps: 1,
dollarsToShow: 25,
dollarsToUnlock: 50,
name: "Cardboard Keyboard",
description: "A poorly crafted cardboard version of a keyboard. Makes a satisfying noise.",
},
},
};
var delay = 0;
function thingClicked(thing) {
if (clicker.generators[thing].cost <= clicker.dollars) {
clicker.dollars -= clicker.generators[thing].cost;
clicker.generators[thing].amount++;
clicker.generators[thing].cost += Math.round(
clicker.generators[thing].cost * 0.15
);
updateGenerators();
/*updateDollarsPerSecond();*/
}
}
function dummyFunction() {
updateDollarsPerSecond();
}
function updateDollarsPerSecond() {
for (i in clicker.generators) {
dummyFunction();
console.log((clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)")
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
}
}
function updateGenerators() {
document.querySelector(".genoptions").innerHTML = "";
for (i in clicker.generators) {
document.querySelector("#dps").innerHTML = (clicker.generators[i].amount * clicker.generators[i].dps).toFixed(1) + " dps(Dollars per Second)";
document.querySelector(
".genoptions"
).innerHTML += `<div><button onclick="thingClicked('${i}');"><h3>${clicker.generators[i].name}(${clicker.generators[i].amount})</h3><p>${clicker.generators[i].description}</p><p class="cost">$${clicker.generators[i].cost}</p><p class="dps">${clicker.generators[i].dps} dps</p></button></div>`;
}
}
function updateDollars() {
if (Cookies.get("clicker") != null && Cookies.get("clicker") != "undefined") {
var clicker1 = JSON.parse(Cookies.get("clicker"));
for (i in clicker.generators) {
if (clicker1.generators[i] == null) {
clicker1.generators[i] = clicker.generators[i];
}
}
clicker = clicker1;
}
updateGenerators();
setInterval(() => {
for (i in clicker.generators) {
clicker.dollars +=
(clicker.generators[i].amount * clicker.generators[i].dps) / 100;
}
if (clicker.dollars != 1) {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollars";
} else {
document.getElementById("counter").innerHTML =
String(clicker.dollars).split(".")[0] + " dollar";
}
delay++;
if (delay >= 40) {
Cookies.set("clicker", JSON.stringify(clicker), {
expires: 100000
});
delay = 0;
}
}, 10);
}
This is a hangman project I'm working on. Inside the guessing function, a for loop is used to add onclick functions to the buttons and another for loop is used to check whether the button's text(a letter) is inside the word. Also a while loop is wrapping these for loops up to check whether the user is out of guesses or he guesses the word. But when I try to run it, browser crashes and I have no clue why it happens.
Also I wonder if I can put the while loop conditions inside the for loop as they works quite similar :/
Here is my code:
window.onload = function() {
var letters = "a b c d e f g h i j k l m n o p q r s t u v w x y z";
var category = ["Premier Leaque Football Teams", "Films", "Cities"];
var wordlist = [
["everton", "liverpool", "swansea", "chelsea", "hull", "manchester-city", "newcastle-united"],
["alien", "dirty-harry", "gladiator", "finding-nemo", "jaws"],
["manchester", "milan", "madrid", "amsterdam", "prague"]
];
var hints = [
["Based in Mersyside", "Based in Mersyside", "First Welsh team to reach the Premier Leauge", "Owned by A russian Billionaire", "Once managed by Phil Brown", "2013 FA Cup runners up", "Gazza's first club"],
["Science-Fiction horror film", "1971 American action film", "Historical drama", "Anamated Fish", "Giant great white shark"],
["Northern city in the UK", "Home of AC and Inter", "Spanish capital", "Netherlands capital", "Czech Republic capital"]
]
var buttons = document.getElementById("buttons");
var showCategory = document.getElementById("show_category");
var hyphens = document.getElementById("hyphens");
var showLives = document.getElementById("show_lives");
var showClue = document.getElementById("show_clue");
var showHint = document.getElementById("show_hint");
var playAgain = document.getElementById("play_again");
letters = letters.split(" ");
var letters_ul = document.createElement("ul");
for (var i = 0; i < letters.length; i++) {
var letters_li = document.createElement("li");
var letters_button = document.createElement("button");
letters_button.innerHTML = letters[i];
letters_li.appendChild(letters_button);
letters_ul.appendChild(letters_li);
}
buttons.appendChild(letters_ul);
initialize = function() {
var c = Math.floor(Math.random() * category.length);
var w = Math.floor(Math.random() * wordlist[c].length);
var word = wordlist[c][w];
var lives = 10;
showCategory.innerHTML = "The Chosen Category is " + category[c];
hyphens.innerHTML = "";
for (var i = 0; i < word.length; i++) {
hyphens.innerHTML += "-";
}
showLives.innerHTML = "You have " + lives + " lives"
showClue.innerHTML = "Clue : -";
showHint.addEventListener("click", function(){
showClue.innerHTML = "Clue : " + hints[c][w];
})
playAgain.addEventListener("click", function(){
initialize();
})
guessing(word, lives);
}
guessing = function(word, lives) {
var button_list = document.querySelectorAll("#buttons ul li button");
var isWord = false;
while (lives > 0 && !isWord) {
for (var i = 0; i < button_list.length; i++) {
button_list[i].addEventListener("click", function(e){
var h = "";
for (var j = 0; j < word.length; j++) {
if (word[j] === e.target.innerHTML) {
h += e.target.innerHTML;
} else if (hyphens.innerHTML[j] === word[j]) {
h += "";
} else {
h += "-";
}
if (hyphens.innerHTML === h && lives > 0) {
lives--;
showLives.innerHTML = "You have " + lives + " lives";
} else if (lives === 0 && !isWord) {
showLives.innerHTML = "Game Over!";
} else if (hyphens.innerHTML === word) {
showLives.innerHTML = "You Win!";
isWord = true;
}
hyphens.innerHTML = h;
}
}
)
}
}
}
initialize();
}
* {
box-sizing: border-box;
}
body {
margin: 0;
background-color: goldenrod;
font-family:'Courier New', Courier, monospace;
text-align: center;
color: white;
}
h1 {
font-size: 50px;
}
h2 {
font-size: 40px;
}
p {
font-size: 25px;
}
#buttons ul {
list-style-type: none;
margin: 0;
padding: 0;
}
#buttons ul li {
display: inline-block;
}
#buttons ul li button {
padding: 10px 15px;
border: 1px solid white;
border-radius: 5px;
background-color: white;
color: goldenrod;
margin: 5px;
}
#buttons ul li button:hover {
background-color: goldenrod;
color: white;
}
#buttons ul li button:active, #buttons ul li button:visited {
opacity: 0.5 !important;
background-color: goldenrod !important;
color: white !important;
}
#hyphens {
font-size: 50px;
}
#hangman {
border: 2px dashed white;
}
.container #show_hint, .container #play_again{
color: white;
background-color: goldenrod;
padding: 20px 40px;
margin: 15px;
border: 1px solid white;
}
.container #show_hint:hover, .container #play_again:hover {
background-color: white;
color: goldenrod;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="hangman">
<meta name="keywords" content="hangman">
<meta name="author" content="Nick Hui">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hangman</title>
<link rel="stylesheet" href="hangman.css">
<script src="hangman.js"></script>
</head>
<body>
<h1>HANGMAN</h1>
<h2>VANILLA JAVASCRIPT HANGMAN GAME</h2>
<p>Use the alphabet below to guess the word, or click hint to get a clue.</p>
<div id="buttons"></div>
<p id="show_category"></p>
<div id="hyphens"></div>
<p id="show_lives">You have 10 lives</p>
<p id="show_clue">Clue: -</p>
<canvas id="hangman"></canvas>
<div class="container">
<button id="show_hint">HINT</button>
<button id="play_again">Play again</button>
</div>
</body>
</html>
This is a typing game that I am working on. I am pretty much done with it except for one problem that I am having. When the person finishes typing all of the words in the turboTypingArray, I call my gameWin() function which assigns the class game-over-win to the div with the id "board" and edits the innerHTML of "board". However, it is only adding the class but not the innerHTML. How can I fix this? I apologize in advance if my code is difficult to understand, I am new o this and still learning.
//CONSTANTS
let duplicate;
const easyWords = ["dog", "cat", "bat", "axe", "hat", "ant", "sat", "rug", "mug", "bet", "art", "can", "day", "box", "egg", "few", "bed", "job", "hot", "men", "use", "sun", "jar", "lip", "flu", "aim", "red", "lid", "ear", "tea", "ski", "oak", "gum", "ham", "mob", "nut", "shy", "van", "elk", "gem", "rap", "fur", "eve", "cry", "mad", "ore", "tax", "six", "pet", "old", "map", "gym", "leg", "bus", "app", "war", "yes", "mud", "rim", "duo"];
const mediumWords = ["house", "beach", "adult", "chief", "funny", "hello", "metal", "sauce", "cocoa", "flags", "upset", "pearl", "trash", "enemy", "pizza", "humor", "eagle", "flame", "cargo", "puppy", "retro", "spark", "bride", "straw", "inbox", "bored", "chalk", "fatal", "hobby", "melee", "bagel", "debug", "amaze", "witch", "stool", "thief", "acorn", "hover", "lever", "merge", "lunar", "debit", "cubic", "erase", "vivid", "waist", "yeast", "syrup", "trunk", "rebel", "lobby", "pasta", "grape", "choir", "jewel", "scoop", "rival", "yacht", "sushi", "bunny"];
const hardWords = ["ability", "battery", "compare", "illness", "weather", "speaker", "package", "organic", "quickly", "regular", "premium", "musical", "journal", "healthy", "economy", "connect", "gallery", "illegal", "parking", "roughly", "success", "accused", "chronic", "unusual", "version", "setting", "message", "removal", "several", "dispute", "tourist", "avocado", "witness", "soldier", "monster", "habitat", "crystal", "younger", "analyze", "nervous", "precise", "trailer", "satisfy", "minimal", "fortune", "genuine", "bizarre", "exhibit", "gesture", "nucleus", "pivotal", "rainbow", "mustard", "lottery", "address", "network", "legally", "cartoon", "horizon", "induced"];
for (var i = 0; i < hardWords.length; i++) {
for (var j = i+1; j < hardWords.length; j++) {
if (hardWords[i] == hardWords[j]) {
duplicate = hardWords[j]
console.log(duplicate)
}
}
}
//VARIABLES
let turboTypingArray = [];
let word
let score = 0;
let attempts = 0;
let correctAttempts = 0;
let answerStreak = 0;
let highestAnswerStreak = 0;
let timeRemaining;
let myTimer;
//EVENT LISTENERS
var input = document.getElementById("user-input");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("input-word").click();
};
});
document.getElementById("easy").onclick = setEasy;
document.getElementById("medium").onclick = setMedium;
document.getElementById("hard").onclick = setHard;
//FUNCTIONS
function init() {
score = 0;
attempts = 0;
correctAttempts = 0;
answerStreak = 0;
highestAnswerStreak = 0;
timeRemaining = 120;
clearInterval(myTimer);
document.getElementById("timer").innerHTML = "2:00";
myTimer = setInterval(updateTimer, 1000);
if (document.getElementById("board").classList.contains("game-over-lose")) {
document.getElementById("board").classList.remove("game-over-lose");
}
if (document.getElementById("board").classList.contains("game-over-win")) {
document.getElementById("board").classList.remove("game-over-win");
}
}
function refresh() {
var newWordBoard = "";
turboTypingArray.forEach((item, i) => {
newWordBoard += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("board").innerHTML = newWordBoard;
}
function setEasy() {
init();
turboTypingArray = easyWords.slice();
document.getElementById("user-input").focus();
refresh();
}
function setMedium() {
init();
turboTypingArray = mediumWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function setHard() {
init();
turboTypingArray = hardWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function CheckInput() {
word = document.getElementById("user-input").value;
if (turboTypingArray.includes(word)) {
correctWord()
}
else {
wrongWord();
}
document.getElementById("user-input").value = "";
refresh();
}
function correctWord() {
answerStreak = answerStreak + 1;
if (answerStreak > highestAnswerStreak) {
highestAnswerStreak = answerStreak
}
score = score + 10 + answerStreak;
attempts = attempts + 1;
correctAttempts = correctAttempts + 1;
for (var i = 0; i < turboTypingArray.length; i++) {
if(turboTypingArray[i] == word) {
turboTypingArray.splice(i, 1);
}
}
checkDone();
}
function wrongWord() {
attempts = attempts + 1;
answerStreak = 0;
alert("das wrong broke boi")
}
function checkDone() {
if (turboTypingArray.length < 1) {
score = score - (attempts - correctAttempts);
alert("kfdskn")
clearInterval(myTimer);
gameWin();
}
}
function gameOver() {
document.getElementById("board").classList.add("game-over-lose");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
}
function gameWin() {
console.log("win");
document.getElementById("board").classList.add("game-over-win");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
}
function updateTimer() {
timeRemaining--
if (timeRemaining > 60) {
timerSeconds = timeRemaining - 60;
timerDisplay = "1:" + timerSeconds;
}
if (timeRemaining < 70) {
timerSeconds = timeRemaining - 60
timerDisplay = "1:0" + timerSeconds;
}
if (timeRemaining < 60) {
timerDisplay = "0:" + timeRemaining;
}
if (timeRemaining < 10) {
timerDisplay = "0:0" + timeRemaining;
}
if (timeRemaining < 1) {
gameOver();
clearInterval(myTimer);
}
document.getElementById("timer").innerHTML = timerDisplay;
}
body {
text-align: center;
font-family: "Roboto", monospace;
color: white;
background-color: black;
}
h1 {
margin: 0 auto;
font-family: "Major Mono Display", monospace;
font-size: 48px;
margin: 2%;
}
input {
border-radius: 25px;
height: 50px;
width: 400px;
font-family: "Major Mono Display", monospace;
margin: auto;
font-size: 37px;
text-align: center;
}
button {
background-color: black;
color: white;
height: 50px;
width: 160px;
font-size: 37px;
}
.difficulty-level {
width: 100px;
padding: 3px 0;
margin: auto;;
margin-top: 5px;
margin-bottom: 5px;
text-align: center;
color: black;
}
.board {
height: 220px;
width: 60px;
margin-bottom: 10px;
}
.board-word {
border: 1px solid white;
height: 40px;
width: 130px;
margin: auto;
text-align: center;
font-size: 30px;
}
.user-input {
margin-top: 10px;
}
.container {
display: flex;
justify-content: center;
align-items: center;
}
.wrap {
flex-wrap: wrap;
height: 400px;
width: 1400px;
}
.game-over-lose {
background-color: rgb(255, 0, 0, 0.2);
font-size: 40px;
color: white;
}
.game-over-win {
background-color: lightgreen;
font-size: 40px;
color: white;
}
#difficulty {
margin-bottom: 10px;
margin: auto;
font-family: "Major Mono Display", monospace;
}
#easy {
color: lightgreen;
border: 1px solid lightgreen;
}
#medium {
color: yellow;
border: 1px solid yellow;
}
#hard {
color: red;
border: 1px solid red;
}
#board {
margin: auto;
}
#font-face {
font-family: "digital-clock";
src: url("../fonts/digital-7.ttf");
}
#timer {
font-size: 80px;
font-family: "digital-clock"
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://fonts.googleapis.com/css?family=Major+Mono+Display" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script defer src="js/app.js"></script>
<title>Turbo Typing</title>
</head>
<body>
<h1>turbo typing</h1>
<h2>Select a Difficulty</h2>
<div id="difficulty" class="">
<div id="easy" class="difficulty-level" >easy</div>
<div id="medium" class="difficulty-level">medium</div>
<div id="hard" class="difficulty-level">hard</div>
</div>
<div id="timer"></div>
<div id="board" class="wrap container">
</div>
<div class='user-input'>
<input id = "user-input" type = "text" value = "" />
<button id="input-word" onclick="CheckInput()">Enter</button>
</div>
</body>
</html>
Must say, it was really hard to find the issue :D.
You are calling refresh() on every input check, it also gets called either on a gameOver() or gameWin(). I have set a flag, gameDone, if its true, I do not refresh. I set gameDone to true on gameWin() or gameOver() and reset it back in a refresh.
To test it out, select the "EASY" level and just enter "DOG".
//CONSTANTS
let duplicate;
const easyWords = ["dog"];
const mediumWords = ["house", "beach", "adult", "chief", "funny", "hello", "metal", "sauce", "cocoa", "flags", "upset", "pearl", "trash", "enemy", "pizza", "humor", "eagle", "flame", "cargo", "puppy", "retro", "spark", "bride", "straw", "inbox", "bored", "chalk", "fatal", "hobby", "melee", "bagel", "debug", "amaze", "witch", "stool", "thief", "acorn", "hover", "lever", "merge", "lunar", "debit", "cubic", "erase", "vivid", "waist", "yeast", "syrup", "trunk", "rebel", "lobby", "pasta", "grape", "choir", "jewel", "scoop", "rival", "yacht", "sushi", "bunny"];
const hardWords = ["ability", "battery", "compare", "illness", "weather", "speaker", "package", "organic", "quickly", "regular", "premium", "musical", "journal", "healthy", "economy", "connect", "gallery", "illegal", "parking", "roughly", "success", "accused", "chronic", "unusual", "version", "setting", "message", "removal", "several", "dispute", "tourist", "avocado", "witness", "soldier", "monster", "habitat", "crystal", "younger", "analyze", "nervous", "precise", "trailer", "satisfy", "minimal", "fortune", "genuine", "bizarre", "exhibit", "gesture", "nucleus", "pivotal", "rainbow", "mustard", "lottery", "address", "network", "legally", "cartoon", "horizon", "induced"];
for (var i = 0; i < hardWords.length; i++) {
for (var j = i+1; j < hardWords.length; j++) {
if (hardWords[i] == hardWords[j]) {
duplicate = hardWords[j]
console.log(duplicate)
}
}
}
//VARIABLES
let turboTypingArray = [];
let word
let score = 0;
let attempts = 0;
let correctAttempts = 0;
let answerStreak = 0;
let highestAnswerStreak = 0;
let timeRemaining;
let myTimer;
let gameDone = false;
//EVENT LISTENERS
var input = document.getElementById("user-input");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("input-word").click();
};
});
document.getElementById("easy").onclick = setEasy;
document.getElementById("medium").onclick = setMedium;
document.getElementById("hard").onclick = setHard;
//FUNCTIONS
function init() {
score = 0;
attempts = 0;
correctAttempts = 0;
answerStreak = 0;
highestAnswerStreak = 0;
timeRemaining = 120;
clearInterval(myTimer);
document.getElementById("timer").innerHTML = "2:00";
myTimer = setInterval(updateTimer, 1000);
if (document.getElementById("board").classList.contains("game-over-lose")) {
document.getElementById("board").classList.remove("game-over-lose");
}
if (document.getElementById("board").classList.contains("game-over-win")) {
document.getElementById("board").classList.remove("game-over-win");
}
}
function refresh() {
gameDone = false;
var newWordBoard = "";
turboTypingArray.forEach((item, i) => {
newWordBoard += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("board").innerHTML = newWordBoard;
}
function setEasy() {
init();
turboTypingArray = easyWords.slice();
document.getElementById("user-input").focus();
refresh();
}
function setMedium() {
init();
turboTypingArray = mediumWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function setHard() {
init();
turboTypingArray = hardWords.slice();
turboTypingArray.forEach((item, i) => {
document.getElementById("board").innerHTML += "<div class='board-word'>" +item + "</div>"
});
document.getElementById("user-input").focus();
refresh();
}
function CheckInput() {
word = document.getElementById("user-input").value;
if (turboTypingArray.includes(word)) {
correctWord()
}
else {
wrongWord();
}
document.getElementById("user-input").value = "";
if (gameDone === false) {
refresh();
}
}
function correctWord() {
answerStreak = answerStreak + 1;
if (answerStreak > highestAnswerStreak) {
highestAnswerStreak = answerStreak
}
score = score + 10 + answerStreak;
attempts = attempts + 1;
correctAttempts = correctAttempts + 1;
for (var i = 0; i < turboTypingArray.length; i++) {
if(turboTypingArray[i] == word) {
turboTypingArray.splice(i, 1);
}
}
checkDone();
}
function wrongWord() {
attempts = attempts + 1;
answerStreak = 0;
alert("das wrong broke boi")
}
function checkDone() {
if (turboTypingArray.length < 1) {
score = score - (attempts - correctAttempts);
alert("kfdskn")
clearInterval(myTimer);
gameWin();
}
}
function gameOver() {
document.getElementById("board").classList.add("game-over-lose");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
gameDone = true;
}
function gameWin() {
console.log("win");
document.getElementById("board").classList.add("game-over-win");
document.getElementById("board").innerHTML = "Score: " + score + "<br>Attempts: " + attempts + "<br>Correct Attempts: " + correctAttempts + "<br>Highest Answer Streak: " + highestAnswerStreak + "<br>Words Remaining: " + turboTypingArray.length + "/60";
gameDone = true;
}
function updateTimer() {
timeRemaining--
if (timeRemaining > 60) {
timerSeconds = timeRemaining - 60;
timerDisplay = "1:" + timerSeconds;
}
if (timeRemaining < 70) {
timerSeconds = timeRemaining - 60
timerDisplay = "1:0" + timerSeconds;
}
if (timeRemaining < 60) {
timerDisplay = "0:" + timeRemaining;
}
if (timeRemaining < 10) {
timerDisplay = "0:0" + timeRemaining;
}
if (timeRemaining < 1) {
gameOver();
clearInterval(myTimer);
}
document.getElementById("timer").innerHTML = timerDisplay;
}
body {
text-align: center;
font-family: "Roboto", monospace;
color: white;
background-color: black;
}
h1 {
margin: 0 auto;
font-family: "Major Mono Display", monospace;
font-size: 48px;
margin: 2%;
}
input {
border-radius: 25px;
height: 50px;
width: 400px;
font-family: "Major Mono Display", monospace;
margin: auto;
font-size: 37px;
text-align: center;
}
button {
background-color: black;
color: white;
height: 50px;
width: 160px;
font-size: 37px;
}
.difficulty-level {
width: 100px;
padding: 3px 0;
margin: auto;;
margin-top: 5px;
margin-bottom: 5px;
text-align: center;
color: black;
}
.board {
height: 220px;
width: 60px;
margin-bottom: 10px;
}
.board-word {
border: 1px solid white;
height: 40px;
width: 130px;
margin: auto;
text-align: center;
font-size: 30px;
}
.user-input {
margin-top: 10px;
}
.container {
display: flex;
justify-content: center;
align-items: center;
}
.wrap {
flex-wrap: wrap;
height: 400px;
width: 1400px;
}
.game-over-lose {
background-color: rgb(255, 0, 0, 0.2);
font-size: 40px;
color: white;
}
.game-over-win {
background-color: lightgreen;
font-size: 40px;
color: white;
}
#difficulty {
margin-bottom: 10px;
margin: auto;
font-family: "Major Mono Display", monospace;
}
#easy {
color: lightgreen;
border: 1px solid lightgreen;
}
#medium {
color: yellow;
border: 1px solid yellow;
}
#hard {
color: red;
border: 1px solid red;
}
#board {
margin: auto;
}
#font-face {
font-family: "digital-clock";
src: url("../fonts/digital-7.ttf");
}
#timer {
font-size: 80px;
font-family: "digital-clock"
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://fonts.googleapis.com/css?family=Major+Mono+Display" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<script defer src="js/app.js"></script>
<title>Turbo Typing</title>
</head>
<body>
<h1>turbo typing</h1>
<h2>Select a Difficulty</h2>
<div id="difficulty" class="">
<div id="easy" class="difficulty-level" >easy</div>
<div id="medium" class="difficulty-level">medium</div>
<div id="hard" class="difficulty-level">hard</div>
</div>
<div id="timer"></div>
<div id="board" class="wrap container">
</div>
<div class='user-input'>
<input id = "user-input" type = "text" value = "" />
<button id="input-word" onclick="CheckInput()">Enter</button>
</div>
</body>
</html>
I have this code below that is able to transfer the array value to another array when i click on it. For Example, when i click on lime it will move into my Green Array The problem is after i JSON.stringify my Green Array it doesn't show the updated value.
So this is the before i add in a value my green array has 5 values.
And this is after I add in a value to my green array as you can see after I move the value in my array count increases but I don't know why when i stringify the array, it doesn't have the value I added in already I want to stringify it because I want to send the updated data to a server. Is there any reason why this is happening ?
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
var randomFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = randomFruits;
function redraw() {
var combineString = '';
$.each(red[key], function(index) {
combineString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.combineclass').html(combineString);
$.each(green[key2], function(index) {
combineString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.combineclass').html(combineString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data) {
if (fruits[i].type === "1") {
red[key].push(data);
} else {
green[key2].push(data);
}
}
}
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#combineid').prepend('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data2) {
if (fruits[i].type === "1") {
k2 = Object.keys(red).find(k => red[k].indexOf(data2) >= 0);
index2 = red[k2].indexOf(data2);
red[k2].splice(index2, 1);
} else {
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0);
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
}
}
}
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').prepend('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
var testing = JSON.stringify(green);
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.randompill:after{
content: "\002B";
float: left;
width:16px;
}
.new-green-fruit:after{
content: "\292B";
float: left;
width:16px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Total Fruits</h3>
<div id="combineid" class="combineclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Random Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>
It is working fine as expected. Look into the code base properly may be you are missing something.
var greenFruits = ["Watermelon", "Durian", "Avacado", "Lime", "Honeydew"];
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));
greenFruits.push("Guava");
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));
This code is executing on all instances of .flow-hold and not just the div below the .title-hold with text that matches the ==.
The reason for this is I need to change the ranges that I use for each of the gauge1, gauge2, gauge3 instances. I have tried $('.flow-hold').next(function(){
but this is not working either......many thanx in advance
$('.title-hold').each(function() {
if ($(this).text() == 'gauge1') {
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 0.0 && ($(this).text()) <= 100.0) {
$(this).css("background-color", "green");
} else if (parseInt($(this).text()) >= 101.0 && ($(this).text()) <= 200.0) {
$(this).css("background-color", "yellow");
} else if (parseInt($(this).text()) >= 300.0 && ($(this).text()) <= 400.0) {
$(this).css("background-color", "red");
} else {
$(this).css("background-color", "purple");
}
});
} else {
//do nothing
}
});
$('.title-hold').each(function() {
if ($(this).text() == 'gauge2') {
$('.flow-hold').each(function() {
if (parseInt($(this).text()) >= 0.0 && ($(this).text()) <= 250.0) {
$(this).css("background-color", "orange");
} else if (parseInt($(this).text()) >= 251.0 && ($(this).text()) <= 345.0) {
$(this).css("background-color", "pink");
} else if (parseInt($(this).text()) >= 346.0 && ($(this).text()) <= 800.0) {
$(this).css("background-color", "brown");
} else {
$(this).css("background-color", "purple");
}
});
} else {
//do nothing
}
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
There is no need for multiple loops. Just loop once and upon each loop iteration check all gauge values and act accordingly.
Also, it's simpler to work with CSS classes, rather than setting inline styles.
Additionally, be careful with your >= and <= values. The way you have it, if a value were 100.5, it wouldn't match any condition. You may not be planning on working with decimal values right now, but by changing the range a bit, you are safeguarded for the future.
See comments inline.
$('.title-hold').each(function() {
let text = $(this).text(); // Get the text of the .title-hold element
// Get a reference to the .flow-hold element that follows it.
// .next() with no arguments will return the next sibline element after the current one.
let next = $(this).next();
// Get the text of the .flow-hold element that follows it and convert to a number.
// The pre-pended "+" here forces a conversion of the string to a number.
let num = +next.text();
// Depending on what the text of the current .title-hold element being looped is...
switch(text){
case 'gauge1':
if(num >= 0 && num <= 100){
next.addClass("green");
} else if(num <= 200){ // <-- NOTE: the previous test already handled values <=100
next.addClass("yellow");
} else if(num <= 400){
next.addClass("red");
} else {
next.addClass("purple");
}
break;
case 'gauge2':
if(num >= 0 && num <= 250){
next.addClass("orange");
} else if(num <= 345){
next.addClass("pink");
} else if(num <= 800){
next.addClass("brown");
} else {
next.addClass("purple");
}
break;
case 'gauge3':
// Repeat the if statement from above, but with appropriate tests and classes
break;
}
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
/* These classes will be conditionally applied */
.green { background-color:green; }
.yellow { background-color:yellow; }
.red { background-color:red; }
.purple { background-color:purple; }
.orange { background-color:orange; }
.pink { background-color:pink; }
.brown { background-color:brown; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
.next() doesn't take a function argument, you just use it to get the element that you want to act on.
Also, the else if statements don't need to check the lower limits. The <= test in the preceding if ensures that the number is above that limit. Your code was also skipping values between 100.0 and 101.0 -- they would end up in the else at the end.
$('.title-hold').each(function() {
var flowHold = $(this).next('.flow-hold');
var nextVal = parseInt(flowHold.text());
if ($(this).text() == 'gauge1') {
if (nextVal >= 0.0 && nextVal <= 100.0) {
flowHold.css("background-color", "green");
} else if (nextVal <= 200.0) {
flowHold.css("background-color", "yellow");
} else if (nextVal <= 400.0) {
flowHold.css("background-color", "red");
} else {
flowHold.css("background-color", "purple");
}
} else if ($(this).text() == 'gauge2') {
if (nextVal >= 0.0 && nextVal <= 250.0) {
flowHold.css("background-color", "orange");
} else if (nextVal <= 245.0) {
flowHold.css("background-color", "pink");
} else if (nextVal <= 800.0) {
flowHold.css("background-color", "brown");
} else {
flowHold.css("background-color", "purple");
}
}
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
Here:
const gaugeConfig = {
'gauge1': {
ranges: [
{
min: 0,
max: 100,
color: 'green'
},
{
min: 101,
max: 200,
color: 'yellow'
},
{
min: 300,
max: 400,
color: 'red'
}
],
defaultColor: 'purple'
},
'gauge2': {
ranges: [
{
min: 0,
max: 250,
color: 'orange'
},
{
min: 251,
max: 345,
color: 'pink'
},
{
min: 346,
max: 800,
color: 'brown'
}
],
defaultColor: 'purple'
},
}
function updateColors(flowHold, config) {
flow = parseFloat(flowHold.text());
flowHold.css("background-color", config.defaultColor);
for( var i=0; i < config.ranges.length; i++ ) {
range = config.ranges[i];
if (flow >= range.min && flow <= range.max) {
flowHold.css("background-color",range.color);
break;
}
}
}
$('.flow-hold').each(function() {
flowHold = $(this);
titleHold = flowHold.prev();
title = titleHold.text();
config = gaugeConfig[title];
if (config)
updateColors(flowHold, config);
});
.title-hold {
width: 100%;
background: #000;
clear: both;
text-align: center;
color: #fff;
font-size: 18px;
}
.flow-hold {
width: 50%;
float: left;
text-align: center;
font-size: 18px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-hold">gauge1</div>
<div class="flow-hold">200</div>
<div class="title-hold">gauge2</div>
<div class="flow-hold">10.5</div>
<div class="title-hold">gauge3</div>
<div class="flow-hold">325.5</div>
<div class="title-hold">gauge4</div>
<div class="flow-hold">201</div>