Javascript Increment counter onclick event

Viewed 1676

I know this might be pretty simple but I cannot see the tree from the wood atm. Please can you help? I have a variable whose initial value is 1 and I want to increment it by 1 every single time the user clicks on a button. I have this code:

let counter = 0;



dPadRight.addEventListener("click", function increment() {
    counter++;
}
);
console.log(counter);
2 Answers

We don't have your html markup, so below I just created a div with ID of 'dPadRight' to add the listener to. I then referenced this in a variable in the javascript code. I assume you're already doing something like this to have a variable called 'dPadRight'.

Based on your comment describing your need to "use [the counter] for other things", I added another "pad" identified as "otherPad". "dPadRight" can serve to increment the counter. "otherPad" can serve to do something with the counter. In the code below, I just log it.

The lesson here is that if you want to use the counter after it's been incremented -- well -- then you can't be referencing it the main javascript body because that's before it's ever had the chance to increment.

let dPadRight = document.querySelector('#dPadRight');
let otherPad = document.querySelector('#otherPad');

let counter = 0;

dPadRight.addEventListener("click", () => {
    counter++;
});

otherPad.addEventListener("click", () => {
    console.log(counter);
});
<div id="dPadRight">
   click to increment counter
</div>
<br/>
<div id="otherPad">
   click to log counter
</div>

Try this

let counter = 1;


let dPadRight = document.getElementById('dPadRight');

dPadRight.addEventListener("click", function() {
   console.log(counter);
   counter++;
   if(counter > 5){
    // just to show that counter is available outside the annonymous 
    // function
     let bla = getCounterValue();
      console.log("Bla Value " + bla);
       }
 
}
);
function getCounterValue(){
   return counter;
}
<button id="dPadRight">Increment Me </button>

Related