Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/Javascript Button Click Counter

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>
like image 308
Jumpoy Avatar asked Mar 14 '14 10:03

Jumpoy


People also ask

How do you count the number of times a button is clicked in 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.


2 Answers

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.

like image 176
ReeCube Avatar answered Sep 19 '22 21:09

ReeCube


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>
like image 45
Sajib Avatar answered Sep 21 '22 21:09

Sajib