Captain BudderChunk
Captain BudderChunk

Reputation: 25

Increment a variable from jQuery .click

So, I'm trying to make a game where basically you click the picture, it disappears, and then 1 is added to a javascript variable.

So, I have this:

<script>
$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});
</script>

and I have some pictures and when you click on them, they disappear. For example:

<center><p><img src="test.jpg" border="0"></p></center>

I just want it so that the code below, as you can see above, adds 1 to a javascript variable called picturesRemoved

<script>
$(document).ready(function(){
  $("p").click(function(){
    $(this).hide();
  });
});
</script>

Upvotes: 0

Views: 719

Answers (2)

Matthew Darnell
Matthew Darnell

Reputation: 4588

Given HTML like this:

<div>
    <a href="" class="showCount">Show Count</a>
    <ul>
        <li>
            <img src="test.jpg" border="0">
        </li>
        <li>
            <img src="test.jpg" border="0">
        </li>
    </ul>
</div>

You could use the following to do what you are trying to accomplish:

$(document).ready(function(){

    var picturesRemoved = 0;

    $('li').click(function(){
        $(this).hide();
        picturesRemoved++;
    });

    $('.showCount').click( function(e){
        e.preventDefault();
        alert(picturesRemoved);
    });
});

var picturesRemoved = 0; sets a default value to the variable and initializes it. picturesRemoved++; will increment the value as an item is selected.

I also included a link and click handler that will show you the current value of the variable as an example of how you could use it in you JS later on.

e.preventDefault(); will prevent the default action of the anchor. Otherwise the anchor will behave based on the set HREF value. alert(picturesRemoved); uses the standard JS alert function to show the variable.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Define the variable (as a global most likely)

var picturesRemoved = 0;

Then increment inside your handler:

picturesRemoved++;

Overall:

$(document).ready(function(){

    var picturesRemoved = 0;        

    $("p").click(function(){
        $(this).hide();
        picturesRemoved++;
    });
});

Upvotes: 4

Related Questions