I made a clicker game on HTML and JavaScript but it didn’t work. When I click the button it should change the counter but it doesn’t
My HTML file (index.html
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clicker Game</title>
</head>
<body>
<h1>Clicker Game</h1>
<p id="click-count">Clicks: 0</p>
<button onclick="click()">Click Me</button>
<script src="script.js"></script>
</body>
</html>
My JavaScript file (script.js
):
var clicks = 0;
function click() {
clicks++;
document.getElementById("click-count").innerHTML = "Clicks: " + clicks;
};
what do you mean “not working?”
I mean when I click the button the score doesn’t change
ok can you send a link to your Repl?
ok well if you use this code instead everything seems to work fine
<button id="click-button">Click Me</button>
let clicks = 0;
document.getElementById("click-button").addEventListener("click", () => {
clicks++;
document.getElementById("click-count").innerText = "Clicks: " + clicks;
});
so I used let
because var
is outdated and I gave the button
an id
because event listeners are better than on<event>
. I also used innerText
instead of innerHTML
I don’t know what the problem was but I’m guessing that it was the onclick
.
2 Likes
system
Closed
June 24, 2023, 2:09am
7
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.