butterybeast butterybeast - 5 months ago 11
Javascript Question

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a

variable = "yes"
. The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.

Was hoping someone would be kind enough to help.

I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)

HTML:

<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>


JS:

var beast
function imageAdd(choice) {
beast = choice;
}

if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}


http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010

Answer

You have just a couple of problems with your code. The first is this:

if (beast = "yes") {

In this case, you're assigning "yes" to beast, not comparing it. Change it to

if (beast == "yes") {

Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.

var beast;
function imageAdd(choice) {
  beast = choice;
  updateUI();
}

function updateUI() {
  if (beast == "yes") {
    document.getElementById('test1').innerHTML += '<img> an image map goes here';
  }
}
Comments