PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 19, 2022

[FIXED] How to check, how often have dynamically created buttons been clicked, individually and in total?

 May 19, 2022     dom, for-loop, javascript, scope, variables     No comments   

Issue

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.


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



Answered By - lior bakalo
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing