I have a simple script that spawns a div element every second using setInterval. The problem I am facing is that the addScore() fires once for each element in the window. So if there are four targets spawned, the addScore() function runs four times.
<div class="wrap">
<div class="intro">
<p>Simply press go and click the circles as fast as you can!</p>
<button class="go" type="button">Go!</button>
</div>
</div>
<script type="text/javascript">
var score = 0; // Starting score for game
function addScore(){
score++;
console.log(score);
}
function spawnTargets() {
$(".wrap").append("<div class='target'>Hello</div>");
$(".target").click(function(){
$(this).hide();
addScore();
});
}
$(".go").click(function() {
$(".intro").toggle();
setInterval(spawnTargets, 1000);
});
</script>