Reputation: 89
I checked in stackoverflow for a solution to this but after trying a few full pages of results, I figured I'd just ask ;)
Sum-up: I have a mini-game where I am offering hints when an item on a list is clicked. There will be a bunch of items on the list but they can only use 3 hints. The text will change from "you have 3 hints" to "2 hints" then "0 hints" When they use all the hints and get to zero nothing else should be counted and the directions under the hint text should change.
What I have working: I have a counter that counts down from 3 when an item on the list is clicked and the "You Have X Hints" updates.
What I need help with: The counter doesn't stop at zero, it just keeps going down into negative numbers if oyu keep clicking the list items. How do I stop it a zero and disable the counter?
The directions paragraph should only change when they reach zero but it shows after first click. How do I only make it show at zero?
Thanks for your help! Here is my fiddle: http://jsfiddle.net/gudinne/ophyfd8t/2/
Code below:
JS
var counter = 3;
$('.itemList li').on('click', function () {
counter--;
if (counter == 0) {
$('.xHints').html(counter + ' Hints');
} else {
$('.xHints').html(counter + ' Hints');
$('.directions').html('New directions');
}
})
HTML
<div class="itemWrapper">
<ul class="itemList">
<li>cat</li>
<li>mouse</li>
<li>cheese</li>
</ul>
<div id="hintBox"> <span class="youHave">You Have</span>
<span class="xHints">3 Hints</span>
<p class="directions">Use a hint by clicking on a name in the list.</p>
</div>
Upvotes: 0
Views: 1547
Reputation: 14450
You need to do equal to or less than zero. Because the counter can get below zero.
var counter = 3;
$('.itemList li').on('click', function () {
counter--;
if (counter <= 0) {
// This will occur once counter reaches zero, or negative numbers
$('.xHints').html(counter + ' Hints');
// If you don't want counter to go below zero, you could reset counter = 1 here
counter = 1;
} else {
// This will occur for all times counter is above 0
$('.xHints').html(counter + ' Hints');
$('.directions').html('New directions');
}
})
Upvotes: 0
Reputation: 824
You need to check if the counter has reached zero already before you decrement it. You can also simplify your code a bit:
if(counter > 0) {
counter--;
if(counter == 0)
$('.directions').html('New directions');
$('.xHints').html(counter + ' Hints');
}
Upvotes: 1