Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a simple script that spawns a div element every second using setInterval. The problem I am facing is that the addScore() fires once for each element in the window. So if there are four targets spawned, the addScore() function runs four times.

<div class="wrap">
    <div class="intro">
        <p>Simply press go and click the circles as fast as you can!</p>
        <button class="go" type="button">Go!</button>
    </div>  
</div>
<script type="text/javascript">

    var score = 0; // Starting score for 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>
share|improve this question

2 Answers 2

When you add the click-event to the .target, you do it with all the divs you previously added! Use this instead:

<script type="text/javascript">

    var score = 0; // Starting score for 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 the event handler to the parent element and filters for click-elements that came from .target.

share|improve this answer
    
Great, makes complete sense as well. Thank you! –  Derek Jul 18 '13 at 5:16

You are binding multiple click events , when ever a call to the function is made

function spawnTargets() {
        $(".wrap").append("<div class='target'>Hello</div>");
        $(".target").click(function(){
            $(this).hide();
            addScore();
        });
    }

Instead you need to delegate the event

Change

$(".target").click(function(){

to

$('.wrap').on("click", ".target", function(){

And move it to outside the function

Code

var score = 0; // Starting score for game

function addScore() {
    score++;
    console.log(score);
}

function spawnTargets() {
    $(".wrap").append("<div class='target'>Hello</div>");
}

$('.wrap').on("click", ".target", function () {
    $(this).hide();
    addScore();
});

$(".go").click(function () {
    $(".intro").toggle();
    setInterval(spawnTargets, 1000);
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.