I have been working on a whack-a-mole project over the last couple weeks and I ran in to an issue maybe a week ago when trying to click on new mole images that are generated. The goal here is to simply generate an image of a mole in a gamespace div, and each mole can be clicked to increase the user's score. When I run the program I am able to click on the first mole image to increase the score counter, but all other moles are not clickable. There are some other functions in here such as randomX() that are not used in this stage. I used those later for generating images in random locations. I would really appreciate any help, thanks in advance!
var userScore = 0; //Global variable for score counter
var gameTimer = 30; //Global variable for game timer
$(document).ready(function() {
$("#start_button").click(function() {
gameStart();
$("#mole").on('click', scoreIncrease);
});
});
function randomY() { //function to calcualte random y-value between 0 and 300
var y = Math.floor((Math.random() * 300) + 0);
return y;
}
function randomX() { //function to calculate random x-value between 0 and 600
var x = Math.floor((Math.random() * 600) + 0);
return x;
}
function scoreIncrease() { //function that adds to user score and updates #score element
userScore++;
$('#score').html(userScore + ' pts');
}
function timerDecrease() { //function that decrements gameTimer and sets text for #timer
$("#timer").html(gameTimer + ' seconds left');
gameTimer--;
setTimeout("timerDecrease()", 1000);
}
function addMole() {
var t = $('#gamespace').append('<img id="mole" src="img/mole.jpg" />');
t = setTimeout(addMole, 3000);
}
function gameStart() {
$('#timer').show(); //show timer
addMole(); //call addMole function
$('#gamespace').css('background-color', 'brown'); //change #gamespace background color
$('#content').css('background-color', 'green'); //change #content background color
timerDecrease();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>