Counting the number of clicks by pressing a button

1k views Asked by At

I am new to coding and using Lab.JS for a project. I have a button that when pressed, it counts the number of clicks made and then logs it in the console. It is important that the number of clicks isn't shown on screen when the button is pressed and is hidden away from the person pressing the button. I just want the clicks to be counted, but I am not sure how to fix the code iAny help would be appreciated.

var clicks = 0;
trigger = function() {
clicks += 1;
document.getElementById("trigger").innerHTML = clicks;
}
console.log(clicks)
<button class="trigger" id="trigger" onclick="trigger()">SUBMIT</button>

3

There are 3 answers

0
Andy On BEST ANSWER

If you didn't want to have a global clicks variable you could encapsulate it within the function itself, and return a closure.

// Default `clicks` to zero
function trigger(clicks = 0) {

  // Return a new function that increases
  // the click count
  return function () {
    console.log(++clicks);
  }
}

// Call trigger and assign the returned function
// to a new variable called counter
const counter = trigger();

// Move the inline `onclick` listener to the JS
// Call `counter` when the button is clicked
const button = document.querySelector('.trigger');
button.addEventListener('click', counter, false);
<button class="trigger">SUBMIT</button>

0
German On

Please try this code.

  <body>
    <button onclick="trigger()">Click Me</button>
    <script>
      // Initiate a global variable a
      var a = 0;
      function trigger() {
        a++;
        console.log(a);
      }
    </script>
  </body>

As long as you make your variable global. It's value will be save only for that page until user will close the page or tab.

1
palaѕн On

Instead of updating the HTML of button you can add a new div and update it with count like:

var clicks = 0;
trigger = function() {
  clicks += 1;
  document.getElementById("display").innerHTML = clicks;
}
#display {
  padding: 20px;
  margin: 10px;
  font-size: 2rem;
}
<div id="display">0</div>
<button class="trigger" id="trigger" onclick="trigger()">SUBMIT</button>