0

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>
1
  • Your top and bottom code bits are the same. Was this on purpose? Commented Feb 12, 2014 at 22:45

2 Answers 2

4

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++;
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

ahh you beat me to it.
0

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.

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.