I have this function that can handle everything I need for my program, but I just need a way to add to the bottom something that can make the function repeat itself.
function main(){
var scoreCounter= 0
var random= Math.floor((Math.random() * 10) 1)
currentTarget= targets[random]
currentTarget.style.display= "block"
currentTarget.addEventListener("click", function(){
currentTarget.style.display= "none"
scoreCounter =1
aimHero.innerHTML= "Score: " scoreCounter
})
}
CodePudding user response:
So in The click call the code to do it again. You are going to have to unbind the event listener so you are not adding multiple clicks to elements when they appear for the second time.
function main() {
var scoreCounter = 0;
var targets = document.querySelectorAll('.target');
var aimHero = document.querySelector('#aimHero');
function nextTarget() {
var random = Math.floor((Math.random() * targets.length));
var currentTarget = targets[random];
currentTarget.style.display = "block";
function performClick() {
currentTarget.style.display = "none";
scoreCounter = 1;
aimHero.innerHTML = "Score: " scoreCounter;
// remove target
currentTarget.removeEventListener("click", performClick);
// do it again
nextTarget();
}
currentTarget.addEventListener("click", performClick);
}
nextTarget();
}
main();
div {
min-height: 50px;
}
.target {
display:none;
background-color:red;
width: 100px;
height: 100px;
}
<div id="aimHero"></div>
<div><div >1</div></div>
<div><div >2</div></div>
<div><div >3</div></div>
<div><div >4</div></div>
<div><div >5</div></div>
CodePudding user response:
PLEASE delegate
This is so much simpler than removing and adding event handlers
let scoreCounter = 0;
const aimHero = document.querySelector('#aimHero');
const container = document.getElementById("container");
const targets = container.querySelectorAll(".target");
const len = targets.length;
targets.forEach(tgt => tgt.hidden = true)
container.hidden = false;
const nextTarget = () => {
const random = Math.floor((Math.random() * len));
var currentTarget = targets[random];
currentTarget.hidden = false;
}
const performClick = e => {
e.target.closest("div").hidden = true;
scoreCounter = 1;
aimHero.innerHTML = "Score: " scoreCounter;
nextTarget();
}
container.addEventListener("click", performClick);
nextTarget();
div {
min-height: 50px;
}
.target {
background-color: red;
width: 100px;
height: 100px;
}
<div id="aimHero"></div>
<div id="container" hidden>
<div><div >1</div></div>
<div><div >2</div></div>
<div><div >3</div></div>
<div><div >4</div></div>
<div><div >5</div></div>
</div>