I have done something similar to this before, and I know this is really close. I'm just trying to make it so that my button increments the javascript variable, and the function then displays the new value.
<html>
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
int clicks = 0;
function click() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="click()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
</body></html>
onclick = (function outer() { let counter = 0; return function inner() { counter++; console. log('ID:' + element.id + 'Number of clicks: ' + counter); }; })(); The counter variable will be unique for every button, so you will have information for each button how many times it was clicked.
Use var
instead of int
for your clicks
variable generation and onClick
instead of click
as your function name:
var clicks = 0;
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
<button type="button" onClick="onClick()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
In JavaScript variables are declared with the var
keyword. There are no tags like int
, bool
, string
... to declare variables. You can get the type of a variable with 'typeof(yourvariable)', more support about this you find on Google.
And the name 'click' is reserved by JavaScript for function names so you have to use something else.
Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"
<html>
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function hello() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onclick="hello()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
</body></html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With