HTML/Javascript Button Click Counter
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>
After looking at the code you're having typos, here is the updated code
var clicks = 0; // should be var not int
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks; //getElementById() not getElementByID() Which you corrected in edit
}
Demo
Note: Don't use in-built handlers, as .click()
is javascript function try giving different name like clickME()
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.