4

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>

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great, makes complete sense as well. Thank you!
0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.