After creating a button and adding Math.floor(Math.random() * 2 + 1) to generate random correct and wrong answers, you also included 5 images as life counters. When a wrong answer is chosen, one of the images is supposed to be hidden or removed. However, two problems are arising: The first issue is that once an image is removed, the process continues and deletes all other images without resetting the random function. The second problem is that it takes two clicks to start deleting the images after a wrong answer. Despite my efforts to fix it, I haven't been able to identify the cause! Feel free to run the code yourself to experience the problem firsthand. If you're able to help, please explain the solution to me!
var button1 = 1;
var span1 = document.getElementById("count1");
var span2 = document.getElementById("count2");
document.getElementById("button1").onclick = function() {
let btn1 = Math.floor(Math.random() * 2 + 1);
if (btn1 == 1) {
if (parseInt(span1.innerHTML) < 10)
span1.innerHTML = parseInt(span1.innerHTML) + 1;
} else if (parseInt(span2.innerHTML) < 5) {
let imageToDelete = 1;
document.getElementById("button1").onclick = function() {
document.getElementById("image_" + imageToDelete).style.visibility = "hidden";
imageToDelete++;
span2.innerHTML = parseInt(span2.innerHTML) + 1;
}
}
}
<input id="button1" type="button" value="click me?" style="height: 100px; width: 100px;">
<div style="margin-top: 40px;"></div>
<div id="output">
<img id="image_1" src="/images/person1.jpg">
<img id="image_2" src="/images/person1.jpg">
<img id="image_3" src="/images/person1.jpg">
<img id="image_4" src="/images/person1.jpg">
<img id="image_5" src="/images/person1.jpg">
</div>
<p id="p1">CORRECT: <span id="count1">0</span></p>
<p id="p2">ERROR: <span id="count2">0</span></p>