HTML/Javascript Button Click Counter

Jumpoy picture Jumpoy · Mar 14, 2014 · Viewed 193.4k times · Source

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>

Answer

ReeCube picture ReeCube · Mar 14, 2014

Use var instead of int for your 'clicks' variable generation and 'onClick' instead of 'click' as your function name:

<html>
<head>
    <title>Space Clicker</title>
</head>

<body>
    <script type="text/javascript">
    var clicks = 0;
    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    </script>
    <button type="button" onClick="onClick()">Click me</button>
    <p>Clicks: <a id="clicks">0</a></p>

</body></html>

In JavaScript variables are declared with the 'var' tag, there are no tags like int, bool, string... to declare variables. You can get the type of an variable with 'typeof(yourvariable)', more support about this you find on Google.

And the name 'click' is reserved by JavaScript for functionnames so you have to use anything else.