javascriptbuttononclickbuttonclicklabjs

Counting the number of clicks by pressing a button


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>


Solution

  • 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>