Reputation: 2728
I am trying to implement a counter in javascript that increments up when a thumbs up button is clicked, and down when the thumbs down is clicked. However, for some reason the first time the user clicks the thumbs down button the counter increments up a single time, after which it begins to increment correctly (down). Can someone have a look over my code and see what's causing this? Code as follows:
<script type="text/javascript">
var counter1 = 0;
</script>
<div class="pastel-vote-block">
<img class="thumbup" onclick="document.getElementById('tallyone').innerHTML = counter1++" src="img/thumb-up-dark.png" height="32" width="32" alt="thumb up">
<p class="tally" id="tallyone">0</p>
<img class="thumbdown" onclick="document.getElementById('tallyone').innerHTML = counter1--" src="img/thumb-down-dark.png" height="32" width="32" alt="thumb down">
</div>
Upvotes: 0
Views: 1096
Reputation: 324
If you place the ++
operator after the variable, counter1 will be incremented after being assigned to innerHTML.
Try with ++counter1
and --counter1
as this will increment before the operator assignment and result in the expected output.
Upvotes: 8
Reputation: 56744
var a = 10, b;
b = a++; // b will be 10, a will be 11
var a = 10, b;
b = ++a; // b will be 11, a will be 11
Upvotes: 0
Reputation: 8354
<script type="text/javascript">
var counter1 = 0;
</script>
<div class="pastel-vote-block">
<img class="thumbup" onclick="document.getElementById('tallyone').innerHTML = ++counter1" src="img/thumb-up-dark.png" height="32" width="32" alt="thumb up">
<p class="tally" id="tallyone">0</p>
<img class="thumbdown" onclick="document.getElementById('tallyone').innerHTML = --counter1" src="img/thumb-down-dark.png" height="32" width="32" alt="thumb down">
</div>
OP used incement and decrement operators incorrectly
Upvotes: 0