javascript - JQuery Function Running Multiple times for Each Element -
i have simple script spawns div element every second using setinterval. problem facing addscore() fires once each element in window. if there 4 targets spawned, addscore() function runs 4 times.
<div class="wrap"> <div class="intro"> <p>simply press go , click circles fast can!</p> <button class="go" type="button">go!</button> </div> </div> <script type="text/javascript"> var score = 0; // starting score game function addscore(){ score++; console.log(score); } function spawntargets() { $(".wrap").append("<div class='target'>hello</div>"); $(".target").click(function(){ $(this).hide(); addscore(); }); } $(".go").click(function() { $(".intro").toggle(); setinterval(spawntargets, 1000); }); </script>
when add click-event .target, divs added! use instead:
<script type="text/javascript"> var score = 0; // starting score game function addscore(){ score++; console.log(score); } function spawntargets() { $(".wrap").append("<div class='target'>hello</div>"); } $(".go").click(function() { $(".intro").toggle(); setinterval(spawntargets, 1000); }); $(".wrap").on('click', '.target', function(){ $(this).hide(); addscore(); }); </script>
the .on-function adds event handler parent element , filters click-elements came .target.
Comments
Post a Comment