Button Becomes Visible after counter reaches threshold - javascript

I am trying to make a simple clicker game that you try and generate money through clicking a button. And I want a upgrade button to become visible after you have $10.
Here is the code:
var money = 0
const addMoneyButton = document.getElementById('Clicker')
const addMoney = () => {
money += 1
document.getElementById("money").innerHTML = money
console.log(money)
function upgrade1() {
var upgrade1 = document.getElementById('upgrade1')
if (money > 10) {
upgrade1.style.visibility = 'visible'
}
}
}
addMoneyButton.addEventListener("click", addMoney)
<button id="Clicker">Click To Begin Making Money</button>
<br>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1>

You forgot to call your function:
var money = 0
const addMoneyButton = document.getElementById('Clicker')
const addMoney = () => {
money += 1
document.getElementById("money").innerHTML = money
console.log(money)
function upgrade1() {
var upgrade1 = document.getElementById('upgrade1')
if (money > 10) {
upgrade1.style.visibility = 'visible'
}
}
// here!
upgrade1()
}
addMoneyButton.addEventListener("click", addMoney)
<button id="Clicker">Click To Begin Making Money</button>
<br>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1>

You can shorten your code to this:
const clicker = document.getElementById('Clicker');
const upgrade1 = document.getElementById('upgrade1');
const money = document.getElementById('money');
let count = 0;
clicker.addEventListener('click', () => {
money.textContent = ++count;
if (count > 10) upgrade1.style.visibility = 'visible';
});
<button id="Clicker">Click To Begin Making Money</button>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1>

Related

Interact between values

I'm wondering how to stop counting money (iloscPieniedzy) when HP (iloscZycia) is 0 in this code:
let iloscZycia = 20;
const sumaZycia = document.getElementById("suma-zycia");
const dodajZycie = document.getElementById('dodaj-zycie');
const odejmijZycie = document.getElementById('odejmij-zycie');
dodajZycie.addEventListener("click", function() {
iloscZycia++;
sumaZycia.textContent = iloscZycia;
});
odejmijZycie.addEventListener("click", function() {
iloscZycia = iloscZycia - 5;
if (iloscZycia <= 0) {
iloscZycia = 0
};
sumaZycia.textContent = iloscZycia;
});
let iloscPieniedzy = 0;
const sumaPieniedzy = document.getElementById("suma-pieniedzy");
const dodajPieniadze = document.getElementById('dodaj-pieniadze');
const odejmijPieniadze = document.getElementById('odejmij-pieniadze');
dodajPieniadze.addEventListener("click", function() {
iloscPieniedzy = iloscPieniedzy + 10;
sumaPieniedzy.textContent = iloscPieniedzy;
});
odejmijPieniadze.addEventListener("click", function() {
iloscPieniedzy = iloscPieniedzy - 1;
if (iloscPieniedzy <= 0) {
iloscPieniedzy = 0
};
sumaPieniedzy.textContent = iloscPieniedzy;
});
I tried something like this:
if (sumaZycia=0){
sumaPieniedzy=0
};
but even this doesn't work like it's not connected.
the = operator is used to assign values to variables what you're looking for is the equality operator ===.
so try it like this:
if (iloscZycia === 0){
iloscPieniedzy = 0
};
Because Stack Overflow is an English language site, I've renamed your variables and created a map of the new names to previous names in comments at the top of the JavaScript below.
If you create a functional closure for updating your numeric variables, you can encapsulate the necessary logic for only updating money when hp is not equal to 0.
Here's a working example in a code snippet:
// hp: iloscZycia
// element1: sumaZycia
// element2: dodajZycie
// element3: odejmijZycie
// money: iloscPieniedzy
// element4: sumaPieniedzy
// element5: dodajPieniadze
// element6: odejmijPieniadze
let hp = 20;
const adjustHp = (amount) => {
hp += amount;
if (hp < 0) hp = 0;
element1.textContent = hp;
};
const element1 = document.getElementById("suma-zycia");
const element2 = document.getElementById("dodaj-zycie");
const element3 = document.getElementById("odejmij-zycie");
element1.textContent = hp;
element2.addEventListener("click", () => adjustHp(1));
element3.addEventListener("click", () => adjustHp(-5));
let money = 0;
const adjustMoney = (amount) => {
// Update money, but ONLY if hp is not 0:
if (hp !== 0) {
money += amount;
if (money < 0) money = 0;
}
element4.textContent = money;
};
const element4 = document.getElementById("suma-pieniedzy");
const element5 = document.getElementById("dodaj-pieniadze");
const element6 = document.getElementById("odejmij-pieniadze");
element4.textContent = money;
element5.addEventListener("click", () => adjustMoney(10));
element6.addEventListener("click", () => adjustMoney(-1));
.group { display: flex; gap: 0.5rem; }
<h2>HP</h2>
<div class="group">
<button id="odejmij-zycie">-</button>
<div id="suma-zycia">0</div>
<button id="dodaj-zycie">+</button>
</div>
<h2>Money</h2>
<div class="group">
<button id="odejmij-pieniadze">-</button>
<div id="suma-pieniedzy">0</div>
<button id="dodaj-pieniadze">+</button>
</div>

Why am I getting 1 number short of my inputted number e.g 10 outputs 9

Building a countdown Timer with rounds, working and resting for training.
Issue: My timer seems to start fine (with the user inputted values) after the first round, once rest is done, my working timer doesn't start at the inputted value like it should. It's always one number short.
E.g If you input 5: 10: 10. When it comes back around, it will appear one number shorter than it should 4: 09: 00
From the left the Timer is rounds, working, rest.
Please help.
let rnd = '00';
let wrk = 00; // this will act as my seconds
let rst = '00';
let prepare =3;
let interval;
let rstInterval;
let startTimer = '00';
// store the working set in an array
let prepIn = document.getElementById('prep');
prepIn.innerHTML = prepare;
// buttons
document.getElementById('start').addEventListener('click', initTimer);
document.getElementById('pause').addEventListener('click', pauseTimer);
document.getElementById('reset').addEventListener('click', finishTimer);
let span= document.getElementById('app').getElementsByTagName('span');
function initTimer(){
clearInterval(interval)
let rounds = document.querySelector('.rounds').value;
rnd = rounds;
span[0].innerHTML = rnd
let work = document.querySelector('.work').value;
wrk = work;
startTimer = work;
span[1].innerHTML =wrk
let rest = document.querySelector('.rest').value;
rst = rest;
span[2].innerHTML = rst
console.log(startTimer)
interval= setInterval(countDown, 1000);
}
// Pause the timer
function pauseTimer(){
clearInterval(interval);
console.log("pauseTimer")
}
// reset timer
function finishTimer(){
clearInterval(interval);
span[0].innerHTML = '00'
span[1].innerHTML = '00'
span[2].innerHTML = '00'
rnd = '00';
wrk = '00';
rst = '00';
document.querySelector('.timeNum').style.display = "flex"
}
function countDown(){
prepare--
if(prepare < 10){
prepIn.innerHTML = '0' + prepare;
}
if(prepare >=9){
prepIn.innerHTML = prepare;
}
if(prepare <= 3){
prepIn.style.color = 'green';
}
if(prepare < 1){
clearInterval(interval)
prepare = 00
prepIn.style.display = 'none'
clearInterval(startTimer)
startTimer= setInterval(timerActive, 1000);
let work = document.querySelector('.work').value;
wrk = work;
console.log(wrk)
}
document.querySelector('.timeNum').style.display = "none";
}
function timerActive(){
wrk--
if(wrk <=9){
span[1].innerHTML = '0' + wrk;
}
if(wrk >=10){
span[1].innerHTML = wrk;
}
if(wrk <= 0){
clearInterval(startTimer)
let rest = document.querySelector('.rest').value;
rst = rest
let rstInterval = setInterval(() => {
rst--
if(rst<=9){
span[2].innerHTML = '0' + rst;
}
if(rst >=10){
span[2].innerHTML = rst;
}
if(rst < 1){
clearInterval(rstInterval)
rstcount();
}
},1000)
rnd--
if(rnd <10){
span[0].innerHTML = '0'+ rnd;
}
else{
span[0].innerHTML = rnd;
}
}
};
function rstcount(){
clearInterval(rstInterval);
countDown();
}
<div class="timer">
<div class="numb">
<h2 id="prep"></h2>
<h2 id="app"><span>00</span>:<span>00</span>:<span>00</span></h2>
<h1 class="timeNum"><input type='number' min="00" max="99" class="rounds" value='00'>:<input type='number' min="00" max="99" class="work" value="00">:<input type='number' min="00" max="99" class="rest" value="00"></h1>
<div class="buttons">
<input type="button" id="start" value="Start">
<input type="button" id="pause" value="Pause">
<input type="button" id="reset" value="Reset">
</div>
</div>
</div>

how to add function current score to final score with javascript

sorry for need your help but I can't resolve this problem...
i've got a current score who's changing when I click on button with id "roll".
When I click on this button the random number is add to the old current score (it's good for me)
the problem is here: when I click on "hold" button, I want the result of all the addition of the current score go to the id="score"
And I can't do that.
I need your help to find the solution please.
this is a part of my html code:
<h3 class="ion-text-center">
Score
</h3>
<div class="ion-text-center" id="score">
0
</div>
</ion-col>
</ion-row>
<ion-row id="bottomRow">
<ion-col class="ion-text-center">
<div>CURRENT</div>
<div id="currentScore">0</div>
</ion-col>
<ion-col class="ion-text-center">
<button class="favorite styled" type="button" id="roll" onclick="rollDice()">
Lancer le dé
</button>
<button class="favorite styled" type="button" id="hold">
Réserver
</button>
and this is my js code:
//création of random number
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min+1) ) + min;
}
// functions for current score
let loseScore = 0;
let addCurrentScore = 0;
function currentScoreLose(){
alert ("Vous avez perdu")
document.getElementById("currentScore").textContent = loseScore;
addCurrentScore = 0;
}
function addCurrentScoreFunction(){
let randomNumber = getRandomInt(1, 6);
if (randomNumber === 1){
currentScoreLose();
} else {
alert (randomNumber)
addCurrentScore += randomNumber;
document.getElementById("currentScore").textContent = addCurrentScore;
let goodScore = document.getElementById("currentScore").textContent;
return goodScore;
}
}
//this function add current score to final score when we click on id hold
let score = document.getElementById("score");
function add (){
score.textContent += addCurrentScoreFunction(goodScore);
}
//here we call functions
let roll = document.getElementById("roll");
let hold = document.getElementById("hold");
roll.addEventListener("click", addCurrentScoreFunction);
hold.addEventListener("click", add);
picture of my problem
This is a variable scope nightmare, but here's my quick take on what you're trying to do. Probably needs some tweaks for lose and what should happen for reserve.
//création of random number
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// functions for current score
let currentScore = 0;
let reserveScore = 0;
function currentScoreLose() {
alert("Vous avez perdu")
document.getElementById("currentScore").textContent = loseScore;
currentScore = 0;
}
function rollDice() {
let randomNumber = getRandomInt(1, 6);
if (randomNumber === 1) {
currentScoreLose();
} else {
console.log(randomNumber);
currentScore += randomNumber;
console.log(currentScore);
document.getElementById("currentScore").textContent = currentScore;
}
}
function reserve() {
reserveScore += currentScore;
console.log(reserveScore);
document.getElementById("reserveScore").textContent = reserveScore;
}
//here we call functions
let roll = document.getElementById("roll");
let hold = document.getElementById("hold");
roll.addEventListener("click", rollDice);
hold.addEventListener("click", reserve);
<span>Score</span>
<span id="reserveScore">0</span>
<br>
<span>CURRENT</span>
<span id="currentScore">0</span>
<br><br>
<button class="favorite styled" type="button" id="roll">
Roll the dice
</button>
<button class="favorite styled" type="button" id="hold">
Reserve
</button>

Create Reset button for a counter

I have this counter. It is a counter that uses Javascript Closure. Can you help me with a reset button?
If you can, to this type of "counter" code, not to another...
HTML CODE
<button type="button" onclick="geo()">Count!</button>
<p id="count">0</p>
JAVASCRIPT CODE
<script>
var count= (function () {
var nr = 0;
return function () {nr+= 1; return nr;}
})();
function geo(){
document.getElementById("count").innerHTML = count();
}
</script>
I'm not even sure what you have right now is working.
const addBtn = document.querySelector('#add');
const resetBtn = document.querySelector('#reset');
const pCount = document.querySelector('#count')
let start = 0;
function add(){
start++
pCount.innerHTML = start
}
function reset(){
start = 0;
pCount.innerHTML = start
}
addBtn.addEventListener('click', add)
resetBtn.addEventListener('click', reset)
<button id="add"> Add </button>
<button id="reset" > Reset </button>
<p id="count"></p>
I don't know much about the closure (seems very interesting...) but moving nr variable outside of your function and then call a reset on nr will reset the counter.
var count = (function() {
var nr = 0;
return function(reset = false) {
nr = reset ? 0 : nr + 1
return nr;
}
})();
function geo() {
document.getElementById("count").innerHTML = count();
}
function reset() {
document.getElementById("count").innerHTML = count(true);
}
<button type="button" onclick="geo()">Count!</button>
<button type="button" onclick="reset()">Reset!</button>
<p id="count">0</p>

How to beat a JavaScript condition riddle?

I am using a foreach loop in php to load data from a mysql table. I'm using the data ID's loaded from the data base and applying it to the button values.
The buttons come in two colors, green and white. The buttons represent likes for liking comments or posts.
The total existing number of likes starts at 6 (div id="total")
white buttons
If button 1 has color of white and you click it, total likes (6) will increase by 1. If you click button 1 again, total likes (7) will decrease by 1.
If button 1, button 2, and button three are clicked, total likes (6) increases by 3 ( 1 for each button). If button 1, button 2 and button 3 are clicked again, the total likes (9) will decrease by 3.
The Puzzle
Green buttons
How do I make it so, When a green button is clicked, the total (6) decrease by 1, and if the button is clicked again, it should increase by 1. Unlike white buttons.
If Green button 3, 5 and 6 are clicked, the total (6) should decease by 3. if the same buttons are clicked again, total (6) increases by 3.
Here is my code
var colorcode = "rgb(116, 204, 49)";
var buttonid = str;
var elem = document.getElementById(buttonid);
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
var initialtotal = parseInt(document.getElementById("total").innerHTML, 10);
var likes = new Array();
function showUser(str) {
////// 1st condition /////
if (theCSSprop == colorcode) {
if (likes[value] == 0 || !likes[value]) {
likes[value] = 1;
} else {
likes[value] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum--
}
}
}
////// 2nd condition /////
else {
if (likes[str] == 0 || !likes[str]) {
likes[str] = 1;
} else {
likes[str] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum++
}
}
}
var tot = initialtotal + sum;
document.getElementById("total").innerHTML = tot;
}
<div id="total" style="width:100px;padding:50px 0px; background-color:whitesmoke;text-align:center;">6 </div>
<!---------------------------------------------------------------------------------------------------------------------->
<button id="5" value="5" onclick="showUser(this.value)">LIKE </button>
<button id="346" value="346" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="128" value="128" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="687" value="687" onclick="showUser(this.value)">LIKE </button>
<button id="183" value="183" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="555" value="555" onclick="showUser(this.value)">LIKE </button>
<!---------------------------------------------------------------------------------------------------------------------->
Instead of passing this.value to showUser(), just pass this. That way, the function can get the value and the style directly, without having to call getElementById() (you're not passing the ID). Then you need to set theCSSprop inside the function, so it's the property of the current button.
To make green buttons alternate direction from increment to decrement, you need a global variable that remembers what it did the last time the function was called.
Also, you don't need to write if(likes[str] == 0 || !likes[str]), since 0 is faley. Just write if(!likes[str]).
var colorcode = "rgb(116, 204, 49)";
var likes = new Array();
var greenIncr = -1;
function showUser(elem) {
var initialtotal = parseInt(document.getElementById("total").innerHTML, 10);
////// 1st condition /////
var str = elem.value;
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
if (theCSSprop == colorcode) {
if (!likes[str]) {
likes[str] = 1;
} else {
likes[str] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum += greenIncr;
}
}
greenIncr = -greenIncr; // revese the direction of green button
}
////// 2nd condition /////
else {
if (!likes[str]) {
likes[str] = 1;
} else {
likes[str] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum++
}
}
}
var tot = initialtotal + sum;
document.getElementById("total").innerHTML = tot;
}
<div id="total" style="width:100px;padding:50px 0px; background-color:whitesmoke;text-align:center;">6 </div>
<!---------------------------------------------------------------------------------------------------------------------->
<button id="5" value="5" onclick="showUser(this)">LIKE </button>
<button id="346" value="346" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="128" value="128" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="687" value="687" onclick="showUser(this)">LIKE </button>
<button id="183" value="183" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="555" value="555" onclick="showUser(this)">LIKE </button>
<!---------------------------------------------------------------------------------------------------------------------->
First naive implementation can look like this
class Counter {
constructor(initial) {
this.initial = initial
this.white = [false, false, false]
this.green = [false, false, false]
}
changeGreen(index) {
this.green[index] = !this.green[index]
}
changeWhite(index) {
this.white[index] = !this.white[index]
}
get total() {
return this.initial + this.white.reduce((total, current) => total + current, 0) + this.green.reduce((total, current) => total - current, 0)
}
}
let counter = new Counter(6)
const render = counter => {
document.querySelector('#total').innerHTML = counter.total
}
render(counter)
;['#first', '#second', '#third'].map((selector, index) => {
document.querySelector(selector).addEventListener('click', e => {
e.target.classList.toggle('pressed')
counter.changeWhite(index)
render(counter)
})
})
;['#fourth', '#fifth', '#sixth'].map((selector, index) => {
document.querySelector(selector).addEventListener('click', e => {
e.target.classList.toggle('pressed')
counter.changeGreen(index)
render(counter)
})
})
.green {
background: #00aa00
}
.pressed {
border-style: inset
}
<div id="total">0</div>
<p>
<button id="first">First</button>
<button id="second">Second</button>
<button id="third">Third</button>
<button id="fourth" class="green">Fourth</button>
<button id="fifth" class="green">Fifth</button>
<button id="sixth" class="green">Sixth</button>
</p>
But after all I've finished with something like
class Counter {
constructor(initial, strategy) {
this.initial = initial;
this.elements = [];
this.strategy = typeof strategy === 'function' ? strategy : () => {}
}
addElement(content, type, next) {
const element = {
content: content,
type: type,
state: false
};
this.elements.push(element);
return next(element, this.elements.length - 1);
}
toggleElementState(index) {
this.elements[index].state = !this.elements[index].state
}
get total() {
return this.strategy(this.initial, this.elements)
}
}
const initialize = () => {
Counter.WHITE = Symbol('white');
Counter.GREEN = Symbol('green');
const counter = new Counter(6, (initial, buttons) => {
return initial +
buttons.filter(button => button.type === Counter.WHITE).reduce((total, current) => total + Number(current.state), 0) +
buttons.filter(button => button.type === Counter.GREEN).reduce((total, current) => total - Number(current.state), 0)
});
const render = counter => {
document.querySelector('#total').innerHTML = counter.total
};
const createButton = (element, index) => {
const button = document.createElement('button');
button.setAttribute('data-id', index);
button.classList.add(element.type === Counter.GREEN ? 'green' : 'none');
button.textContent = element.content;
document.querySelector('#buttons').appendChild(button)
};
const addButton = (type, ...selectors) => {
selectors.forEach(selector => counter.addElement(selector, type, createButton));
};
render(counter);
addButton(Counter.WHITE, '#first', '#second', '#third');
addButton(Counter.GREEN, '#fourth', '#fifth', '#sixth');
addButton(Counter.WHITE, '#first', '#second', '#third');
document.querySelector('#buttons').addEventListener('click', function(e) {
e.target.classList.toggle('pressed');
counter.toggleElementState(parseInt(e.target.dataset.id));
render(counter)
})
};
document.addEventListener('DOMContentLoaded', initialize);
.green {
background: #00aa00
}
.pressed {
border-style: inset
}
<div id="total">0</div>
<p id="buttons">
</p>

Categories

Resources