EddNewGate
EddNewGate

Reputation: 537

How to count divs on click in setInterval function

I wrote this code to count when the user clicks on a square (div)

var run = false;
$(document).on('click', function(){
  if(run) return;
  run = true;
  setInterval(function(){
    $("#div").removeClass();
    $("#div").addClass("square").clone().appendTo("#container");
    $(".square").click(function(){
      $('#score').html(function(x, val) { return val*1+1 })
    })
  },2000)
})

but the problem is that when I click a square again, it adds one for each div present onscreen, I want just one point to be added.

Here is in action: http://jsfiddle.net/gwxfvesn/

How can I fix that?

Upvotes: 0

Views: 144

Answers (1)

user3310334
user3310334

Reputation:

It's because, while you are using setInterval, you (re-)add the click event listener to every square, not just the new one.

When you create an element, just chain on .click, so that it applies only to that element:

var run = false;

$(document).on('click', function(){
    if(run) return;
    run = true;
    setInterval(function(){
        $("#div").removeClass();
        $("#div").addClass("square").clone().appendTo("#container").click(function(){
            $('#score').html(function(x, val) { return val*1+1 });
        });
    },2000)
})
.square {
    width: 60px;
    height: 60px;
    background-color: black;
    border: 1px solid black;
    float: left;
    margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="container" style="width: 100%; height:700px">
<div id="score">0</div>
<div id="div"></div>
</div>

You need to add the click listener only to the new element.

Upvotes: 1

Related Questions