Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript check if dynamically created buttons are clicked multiple times

I created a loop with buttons in it. I also created an eventListener that keeps a count for every button. I want something to happen when all buttons have been presses at least 3 times, so I created an if statement that checks if the count is 3 and adds 1 to another count, but the other count stays on 1 even if multiple buttons have been pressed 3 times.

for (let i = 0; i < 7; i++) {
  let btn = document.createElement('button');

  btn.classList.add('buttons');
  btn.id = 'button' + i;

  document.getElementById('box').appendChild(btn);

  let count = 0;
  let count2 = 0;

  btn.addEventListener('click', () => {
    count++;
    console.log(count);

    if (count === 3) {
      console.log('3');

      count2++;
      console.log(count2);
    } else {

      console.log('not 3');
    }
  });
}
#box button { min-width: 20px; min-height: 20px; }
.as-console-wrapper { max-height: 87%!important; }
body { margin: 0; }
<div class="box" id="box">
</div>

So the count variable works fine, and when 1 button has been clicked 3 times the count2 variable changes to 1, but it stays on 1 and I can’t seem to find out why. At the end count2 should be 7, because there are 7 buttons.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

as Vladimir implied in the comments its a scoping problem.

The variable count is only declared inside the event listener, so later on when you press different button your code does count++ for a different count variable.

To solve this declare var count instead of let count – that will make it global.

Or declare the count variable before the for loop.

BTW: make sure to stop updating count as it gets to 3, since it wouldn’t update count2 if it gets to 4 or above

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading