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;
})
Subtract it from x
instead of putting it into a new variable.
https://jsfiddle.net/sean7777/fvgchjb3/1/