I want to build a cookie clicker for a project. With each click on an image, the clicks are counted and displayed. Now I want the image to change automatically after 10000 clicks, i.e. a new image replaces the old one and the current number of clicks is saved in local storage.
It doesn't quite work for me. Only when I save the page and then reload it is the picture changed and not automatically.
if (clickercount >= 10000) {
$(".clickImg").attr("src", "new_image.png")
} else {
}
$('#saveButton').click(function () {
saveCurrentStatus()
});
$('#resetButton').click(function () {
localStorage.clear();
location.reload(true)
});
CodePudding user response:
Judging from the information above, it seems like you are only executing the code once. And that happens only when you load the page. You could use an event listener to listen for clicks on your cookie, and run the piece of code in the event listener.
$('.clickImg').click(function () {
if (clickercount >= 10000) {
$(".clickImg").attr("src", "new_image.png")
} else {
}
});
CodePudding user response:
If I interpret your code correctly, then the if-else block only runs on the first load. You should check that on each click event. Maybe at the end of saveCurrentStatus
, or even better, create a checkClickCount
function, and append it to the click event handler.