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>
Related
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);
}
I have made 3 buttons (10 $, 20 $ ,50$)
and i want when someone clicks a button to add the previous value.
But i get something like this when i click on my buttons 1020502010
Something im doing wrong in this part of the code
// function betBtn()
function bet10 () {
chipbeted.textContent += betc.bet10
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet20 () {
chipbeted.textContent += betc.bet20
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet50 (){
chipbeted.textContent += betc.bet50
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
let player = {
Name : "Nik",
Chips: 150
}
let cards = []
let sum = 0
let hasBlackjack = false
let isAlive = false
let betOn = false
let betc ={
bet10 : 10,
bet20 : 20,
bet50 : 50
}
let message = ""
let messageEl = document.getElementById("message-el")
let totalBet = document.getElementById("chipCount").textContent
let sumEl = document.querySelector("#sum-el")
let cardsEl = document.getElementById("cards-el")
let chipbeted = document.getElementById("chipCount")
let playerEl = document.getElementById("playerEl")
playerEl.textContent = player.Name +":" +" " + player.Chips + "$"
console.log(cards)
function getRandomCard () {
let randomNumer = Math.floor( Math.random()*13 ) + 1
if (randomNumer > 10) {
return 10
} else if (randomNumer === 1) {
return 11
} else {
return randomNumer
}
}
let randomCard = getRandomCard()
function startGame (){
if (betOn === true){
isAlive = true
let firstCard = getRandomCard()
let secondCard = getRandomCard()
cards = [firstCard, secondCard]
sum = firstCard + secondCard
$('.class').css('visibility', 'hidden');
}
else if (betOn === false){
document.getElementById("messagewl").textContent = "First, select how many chips you want to BET"
sum= ""
}
renderGame()
}
function renderGame(){
cardsEl.textContent = "Cards: "
for ( let i=0; i<cards.length ; i++){
cardsEl.textContent += cards[i] + " "
}
sumEl.textContent = "Sum: " + sum
if ( sum <= 20) {
console.log(sum)
message = "Do you want to draw a new card? "
}
else if ( sum === 21){
console.log(sum)
message = "You've got Blackjack!"
hasBlackjack = true
}
else {
console.log(sum)
message = "You're out of the game!"
isAlive = false
}
messageEl.textContent = message
sumEl.textContent = "Sum: " + sum
}
function cardNew(){
if (isAlive === true && hasBlackjack === false) {
let card = getRandomCard()
sum += card
cards.push(card)
console.log(cards)
renderGame()
}
}
// function betBtn()
function bet10 () {
chipbeted.textContent += betc.bet10
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet20 () {
chipbeted.textContent += betc.bet20
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet50 (){
chipbeted.textContent += betc.bet50
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
html, body{
background-image: url("space.png");
background-size: cover;
background-attachment: fixed;
}
body {
color: aliceblue;
font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif ;
text-align: center;
margin-top: 30px;
}
#h1 {
text-align: center;
}
h1 {
font-size: 4em;
display: inline-block;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
border-radius: 100px;
border: 30px;
padding: 0 10px;
text-align: center;
}
#buttons {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 10px;
}
p{
font-size: 2em;
}
#btn {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
width:250px;
font-size: 2.5em;
color: aliceblue;
}
#btnBet > #btn10,#btn20,#btn50{
margin-top: 20px;
font-size: 30px;
font-weight: bold;
justify-content: center;
margin: 20 15 0 15;
}
<html lang="en">
<head>
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blackjac Game</title>
</head>
<body>
<div class="h1">
<h1>Space Blackjack</h1>
</div>
<p id="message-el">Want to play a round?</p>
<p id="cards-el">Cards:</p>
<p id="sum-el">Sum:</p>
<p class= "class" id="messagewl"></p>
<div id="buttons">
<button id="btn" onclick="startGame()">Start Game</button>
<button id="btn" onclick="cardNew()">Draw Card</button>
<button id="btn" onclick="bet()">Bet Chips</button>
</div>
<div id="btnBet">
<button id="btn10" onclick="bet10()">10$</button>
<button id="btn20" onclick="bet20()">20$</button>
<button id="btn50" onclick="bet50()">50$</button>
</div>
<p id="chipCount"></p>
<p id="playerEl"></p>
<script src="index.js"></script>
</body>
This is happening because the variable chipbeted.textContent returns a string .. that's why you get concatenated result (for example: '20'+10 = 2010 not 30
)..
to solve this problem,
let chipbeted = document.getElementById("chipCount")
let betc = {
bet10: 10,
bet20: 20,
bet50: 50
}
function bet20() {
chipbeted.textContent = Number(chipbeted.textContent) + betc.bet20
//betOn = true
//$('.class').css('visibility', 'hidden');
//console.log(chipbeted.textContent)
}
<button onClick="bet20()">Add bet20</button>
<p id="chipCount"></p>
replace
chipbeted.textContent += betc.bet20
in your functions
with
chipbeted.textContent = Number(chipbeted.textContent) + betc.bet20
Salam . Try this in your function betBtn() :
chipbeted.textContent=parseInt(chipbeted.textContent)+betc.betBtn ;
Instead of this :
chipbeted.textContent += betc.betBtn
You have to convert the text fields value to Number first, than add the value to it. Otherwise the "+" operator means string concatenation.
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet20
let player = {
Name : "Nik",
Chips: 150
}
let cards = []
let sum = 0
let hasBlackjack = false
let isAlive = false
let betOn = false
let betc ={
bet10 : 10,
bet20 : 20,
bet50 : 50
}
let message = ""
let messageEl = document.getElementById("message-el")
let totalBet = document.getElementById("chipCount").textContent
let sumEl = document.querySelector("#sum-el")
let cardsEl = document.getElementById("cards-el")
let chipbeted = document.getElementById("chipCount")
let playerEl = document.getElementById("playerEl")
playerEl.textContent = player.Name +":" +" " + player.Chips + "$"
console.log(cards)
function getRandomCard () {
let randomNumer = Math.floor( Math.random()*13 ) + 1
if (randomNumer > 10) {
return 10
} else if (randomNumer === 1) {
return 11
} else {
return randomNumer
}
}
let randomCard = getRandomCard()
function startGame (){
if (betOn === true){
isAlive = true
let firstCard = getRandomCard()
let secondCard = getRandomCard()
cards = [firstCard, secondCard]
sum = firstCard + secondCard
$('.class').css('visibility', 'hidden');
}
else if (betOn === false){
document.getElementById("messagewl").textContent = "First, select how many chips you want to BET"
sum= ""
}
renderGame()
}
function renderGame(){
cardsEl.textContent = "Cards: "
for ( let i=0; i<cards.length ; i++){
cardsEl.textContent += cards[i] + " "
}
sumEl.textContent = "Sum: " + sum
if ( sum <= 20) {
console.log(sum)
message = "Do you want to draw a new card? "
}
else if ( sum === 21){
console.log(sum)
message = "You've got Blackjack!"
hasBlackjack = true
}
else {
console.log(sum)
message = "You're out of the game!"
isAlive = false
}
messageEl.textContent = message
sumEl.textContent = "Sum: " + sum
}
function cardNew(){
if (isAlive === true && hasBlackjack === false) {
let card = getRandomCard()
sum += card
cards.push(card)
console.log(cards)
renderGame()
}
}
// function betBtn()
function bet10 () {
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet10;
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet20 () {
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet20 ;
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
function bet50 (){
chipbeted.textContent = Number(chipbeted.textContent)+betc.bet50;
betOn = true
$('.class').css('visibility', 'hidden');
console.log(chipbeted.textContent)
}
html, body{
background-image: url("space.png");
background-size: cover;
background-attachment: fixed;
}
body {
color: aliceblue;
font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif ;
text-align: center;
margin-top: 30px;
}
#h1 {
text-align: center;
}
h1 {
font-size: 4em;
display: inline-block;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
border-radius: 100px;
border: 30px;
padding: 0 10px;
text-align: center;
}
#buttons {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 10px;
}
p{
font-size: 2em;
}
#btn {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
background: linear-gradient(246.26deg, #ED4683 0%, #F48E14 100%);
width:250px;
font-size: 2.5em;
color: aliceblue;
}
#btnBet > #btn10,#btn20,#btn50{
margin-top: 20px;
font-size: 30px;
font-weight: bold;
justify-content: center;
margin: 20 15 0 15;
}
<html lang="en">
<head>
<link rel="stylesheet" href="index.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>blackjac Game</title>
</head>
<body>
<div class="h1">
<h1>Space Blackjack</h1>
</div>
<p id="message-el">Want to play a round?</p>
<p id="cards-el">Cards:</p>
<p id="sum-el">Sum:</p>
<p class= "class" id="messagewl"></p>
<div id="buttons">
<button id="btn" onclick="startGame()">Start Game</button>
<button id="btn" onclick="cardNew()">Draw Card</button>
<button id="btn" onclick="bet()">Bet Chips</button>
</div>
<div id="btnBet">
<button id="btn10" onclick="bet10()">10$</button>
<button id="btn20" onclick="bet20()">20$</button>
<button id="btn50" onclick="bet50()">50$</button>
</div>
<p id="chipCount"></p>
<p id="playerEl"></p>
<script src="index.js"></script>
</body>
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>
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));
I would like to toggle between degree's and fahrenheit when the temperature is clicked.
I have managed to do this when it is clicked on degree's it is changed to fahrenheit, but now how do i change it back to degree's when clicked on fahrenheit?
temp.addEventListener('click', degreeToF);
function degreeToF() {
const f = manchester.current.temp_c * 1.8 + 32;
temp.innerHTML = f.toFixed(0) + '<span class="degrees"> f </span>';
}
Here is my codepen: https://codepen.io/o-sewell/pen/mRyEyW
var showing = 'F';
temp.addEventListener('click', degreeToF);
function degreeToF() {
if(showing === 'F'){
// convert to C
showing = 'C';
const f = (manchester.current.temp_c - 32 ) * 5/9;
temp.innerHTML = f.toFixed(0) + '<span class="degrees"> c </span>';
} else {
// convert to
showing = 'F';
const f = manchester.current.temp_c * 1.8 + 32;
temp.innerHTML = f.toFixed(0) + '<span class="degrees"> f </span>';
}
}
Here you go. Used simple boolean value to tell the function which part of code to execute.
CodePen link
const weather = 'https://api.apixu.com/v1/current.json?key=cd93499e97644fcc873154715163112&q=Manchester';
const baseColors = ["#C2272D", "#F8931F", "#FFFF01", "#009245", "#0193D9", "#0C04ED", "#612F90"];
const tintColors = ["#F8DDDE", "#FEDBB4", "white", "#0193D9", "#009245", "#E7E6F9"];
let manchester = [];
fetch(weather)
.then((blob) => blob.json())
.then((data) => manchester = data)
.then((data) => displayWeather(data));
let iconWeather = document.querySelector('#weather');
let temp = document.querySelector('#temp');
let textLocation = document.querySelector('#text-location');
let textWeather = document.querySelector('#text-weather');
function displayWeather() {
iconWeather.src = manchester.current.condition.icon;
temp.innerHTML = manchester.current.temp_c + '<span class="degrees"> c </span>';
textLocation.innerHTML = manchester.location.name;
textWeather.innerHTML = manchester.current.condition.text;
};
const background = document.querySelector('.weather');
window.addEventListener('load', changeBackground);
function changeBackground() {
let random = Math.floor(Math.random() * baseColors.length);
let randomBaseColor = baseColors[random];
let randomTintColor = tintColors[random];
background.style.background = 'linear-gradient(0deg,' + randomBaseColor + ',' + randomTintColor + ')';
background.style.transition = 'background , 2s, ease';
}
setInterval(changeBackground, 2500);
temp.addEventListener('click', degreeToF);
var x = true;
function degreeToF() {
if (x) {
const f = manchester.current.temp_c * 1.8 + 32;
temp.innerHTML = f.toFixed(0) + '<span class="degrees"> f </span>';
x = !x;
} else {
const f = manchester.current.temp_c;
temp.innerHTML = f.toFixed(0) + '<span class="degrees"> c </span>';
x = !x;
}
}
* {
box-sizing: border-box;
}
.wrapper {
margin: 50px;
}
.weather {
max-width: 90%;
margin: 0 auto;
background: pink;
padding: 20px;
box-shadow: 0 5px rgba(0, 0, 0, 0.1);
border-radius: 6px;
}
#media (min-width: 800px) {
.weather {
max-width: 40%;
}
}
.weather__temperature {
margin-top: 50px;
text-align: center;
}
.weather__temperature--temp {
font-size: 80px;
cursor: pointer;
}
.weather__text {
text-align: center;
}
.weather__text--description {
color: black;
font-size: 18px;
}
.weather__icon {
margin-top: 5px;
}
.weather__icon--image {
display: block;
margin: 0 auto;
padding: 5px 0;
width: 150px;
height: auto;
}
.weather__location {
text-align: center;
}
.weather__location--text {
letter-spacing: 5px;
font-size: 22px;
margin-bottom: 50px;
}
.degrees {
color: red;
font-size: 20px;
}
<div class="wrapper">
<div class="weather">
<div class="weather__temperature" />
<p class="weather__temperature weather__temperature--temp" id="temp"></p>
</div>
<div class="weather__text">
<p class="weather__text weather__text--description" id="text-weather"></p>
</div>
<div class="weather__icon">
<img class="weather__icon weather__icon--image" id="weather" src="" />
</div>
<div class="weather__location">
<p class="weather__location--text" id="text-location"></p>
</div>
</div>
</div>