Skip to content
Advertisement

beginner javascript button

I’m really struggling with a basic javascript problem and I can’t find the right way to Google help. I’ve been practicing Javascript, but thus far I’ve mainly been just following prompts, not coding my own ideas. I genuinely tried to solve this problem on my own for several hours. This is my very first attempt at generating my own javaScript from scratch.

Basically, I’m just trying to do something like a choose your own adventure story. The idea is the p element in the html changes with yes and no responses. For some reason, my javascript code skips over my if and goes to my else, meaning that the first condition was not met. For the life of me, I cannot figure out how to meet that first if condition when the user clicks “yes”. Any advice?

function beginWalk() {
  var start = "You go outside. It's a beautiful day!";
  var stay = "You stay inside and snuggle up in your bed.";

  {
    if (document.getElementById("yes").click == true) {
      document.getElementById("change").innerHTML = start;
    } else {
      document.getElementById("change").innerHTML = stay;
    }
  }
}
<button onclick="beginWalk()" value="true" id="yes">Yes</button>
<button onclick="beginWalk()" value="false" id="no">No</button>
<p id="change">
  change
</p>

Advertisement

Answer

Easy solution would be to pass the arguments you need in your button click event and base your conditions on it.

function beginWalk(walk) {
  const start = "You go outside. It's a beautiful day!";
  const stay = "You stay inside and snuggle up in your bed.";

  if (walk === true) {
    document.getElementById("change").innerText = start;
  } else {
    document.getElementById("change").innerText = stay;
  }
}
<button onclick="beginWalk(true)" value="true" id="yes">Yes</button>
<button onclick="beginWalk(false)" value="false" id="no">No</button>
<p id="change">
  change
</p>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement