0

So I have some HTML code here:

<body>
<b style="font-size: 26px;">How the game works</b>
<u id="HowToPlay_HideShow" style="color: #9FF;">[hide]</u><br>
</body>

And I also used Javascript to turn the hide text into show, and show back into hide when clicked on.

<script>
var HowGameWorks_Hidden = false;
document.getElementById("HowToPlay_HideShow").onclick = function () {
    if (HowGameWorks_Hidden == false) {
        document.getElementById("HowToPlay_HideShow").innerHTML = "[show]";
        HowGameWorks_Hidden = true;
    }
    if (HowGameWorks_Hidden == true) {
        document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
        HowGameWorks_Hidden = false;
    }
}
</script>

This, however, does not seem to work. Clicking on the hide and show text has no effect at all. So I tried removing this piece of code:

if(HowGameWorks_Hidden == true) {
    document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
    HowGameWorks_Hidden = false;
  }

And it correctly turns the hide text into show when I click it (but, of course, does not turn the show text back into hide).

So how do I get my code working?

1 Answer 1

3

This is because your second if statement will always get triggered if your first one does, since you set HowGameWorks_Hidden to true in it. You need to use an else:

if(HowGameWorks_Hidden == false) {
  document.getElementById("HowToPlay_HideShow").innerHTML = "[show]";
  HowGameWorks_Hidden = true;
}

else if(HowGameWorks_Hidden == true) {
  document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
  HowGameWorks_Hidden = false;
}
Sign up to request clarification or add additional context in comments.

2 Comments

But why? Why can't I simply use an If-statement instead of else? (Anyway it works now, thanks)
Read my edit, I added a bit of an explanation. Walk through what happens when HowGameWorks_Hidden is false - you hit your first if statement and as a result set HowGameWorks_Hidden to true. Now you hit your second if...and so you set HowGameWorks_Hidden to false. The else prevents you from going into the second if statement if the first succeeds.

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.