0

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>
0

3 Answers 3

8

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.

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

1 Comment

Who in heck wrote JS this way! My lord!
0
<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

2 Comments

Dont just post code and have people guess what you have changed.
What have you changed ? Why ?
0
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

2 Comments

This does answer the question. Answer must not always be explicit. Answers, especially if given in the form of extremely simplified and short code snippets, can also be implicit.
As a quick note, perhaps consider adding some textual explanation outside of the code block. Code-only answers tend to be low-quality, as while they give the OP an example, later users (and potentially even the OP) may not understand what's going on. (I know you added a bit of an explanation in the comments on the code, but textual explanation can go a long way towards the quality of an answer and the understandablity of an answer.)

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.