Home > OS >  It seems click button doesnt respond and increment the number each click
It seems click button doesnt respond and increment the number each click

Time:01-18

here his my code, i cant figure out what am i missing, when click on INCREMENT button nothing happens: (note that is on codeopen so i dont need to connect between html to js)

html:

<div >
  
<div id="displayScreen">-</div>
    <div id="container-btn">
      <button id="reset">reset</button>
      <button id="increment">increment</button>
    </div>
  
</div>

JS:

let increment = document.getElementById("increment")
increment.addEventListener("click", plus());
let count = 0                          
function plus() {
    let count = 0 
    document.getElementById("displayScreen").innerText= count     
 
}
                        

CodePudding user response:

I noticed few problmes:

  1. You initiallize count to be 0 every time plus is called.
  2. count means first assign, that increment. This way, the first time you click on increment, the value will be still 0, and not 1 as you want.
  3. addEventListener should get a callback on the 2nd parameter (a function that should be invoked when clicking the button. What you did is invoking plus in the 2nd paramer, returning undefined (since there's no return statement in plus), to addEventListener.

I added to working code:

let increment = document.getElementById("increment");
increment.addEventListener("click", plus);
let count = 0;

function plus() {
  document.getElementById("displayScreen").innerText =   count;
}
<div id="displayScreen">-</div>
<div id="container-btn">
  <button id="reset">reset</button>
  <button id="increment">increment</button>
</div>

  •  Tags:  
  • Related