I'm working on a project and am a bit stuck. I am sure I am missing something but have not what exactly I'm missing.
I extracted the general concept of what I'm doing and threw it onto a JS fiddle.
So basically, I am wanting to decrement the displayed number (200) by a randomly generated number between a specified number range every time the button is clicked (using vanilla JS). Got it to work a bit. When the button is clicked, it does decrement.
However I am wanting to continue to decrement it until the displayed number is 0. The issue I'm running into however is, every time the button is clicked the displayed number updates but still subtracting from 200, not from the updated value.
For example, I can click once and the number will jump from 200 down to 189. When I click again, the number will actually jump up to say 195, meaning it's subtracting from 200 rather than subtracting the new generated amount from 189.
Jsfiddle: https://jsfiddle.net/miguerurso/0wmtgd67/5/
html:
<head></head>
<body>
<div id="number" style="font-size: 2em;"></div>
<button>decrement</button>
</body>
JS:
const numberCont = document.getElementById('number');
const button = document.querySelector('button');
let x = 200;
numberCont.innerHTML = x;
button.addEventListener("click", function(){
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min 1) min)
}
const randomNumResult = randomNum(7, 12)
let updatedX = x - randomNumResult;
numberCont.innerHTML = updatedX;
})
CodePudding user response:
Subtract it from x
instead of putting it into a new variable.
https://jsfiddle.net/sean7777/fvgchjb3/1/
CodePudding user response:
You need assign the updateX
To x as well. Currently you are only giving it to the element. Try this.
const numberCont = document.getElementById('number');
const button = document.querySelector('button');
let x = 200;
numberCont.innerHTML = x;
button.addEventListener("click", function(){
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min 1) min)
}
const randomNumResult = randomNum(7, 12)
x = Math.floor(0, x - randomNumResult);
numberCont.innerHTML = x;
}
CodePudding user response:
You're not actually changing the value of x
to the new subtracted value. You'll have to do this to keep subtracting from the variable. I rewrote your event listener to change the value of x
without going below 0.
button.addEventListener("click", function(){
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min 1) min)
}
x = Math.max(x - randomNum(7, 12), 0);
numberCont.innerHTML = x;
})
CodePudding user response:
Just change one line of code:
let updatedX = x - randomNumResult;
numberCont.innerHTML = updatedX;
with:
x = x - randomNumResult;
numberCont.innerHTML = x;