kinezu
kinezu

Reputation: 1272

Inconsistent behavior when updating a background image using JavaScript

I have 5 buttons that have background images. Before changing an image on 'button1', I am making sure that all of the other buttons return to their original state. After that, I am changing 'button1' to a new image (I am not sure if this is the best way to do this).

About half of teh times I visit the page, this works as intended. The other times, 'button1' does not get set and remains unchanged. Why does this not work the same each time? How can I make the behaviour be consistent?

document.getElementById("button2").style.backgroundImage = "url('Images/buttonUnClicked.png')";
document.getElementById("button3").style.backgroundImage = "url('Images/buttonUnClicked.png')";
document.getElementById("button4").style.backgroundImage = "url('Images/buttonUnClicked.png')";
document.getElementById("button5").style.backgroundImage = "url('Images/buttonUnClicked.png')";

document.getElementById("button1").style.backgroundImage = "url('Images/buttonClicked.png')";

Upvotes: 1

Views: 80

Answers (1)

Alon Dahari
Alon Dahari

Reputation: 1147

This is the description of radio inputs. You don't need JavaScript for that.
The trick is to style the labels to the radio buttons and hide the buttons themselves.

HTML:

<form>
  <ul>
    <li>
      <input type="radio" class="button" name="button" id="button1"/>
      <label for="button1"></label>
    </li>
  </ul>
</form>  

(add as many buttons as you want)

CSS:

ul {
  list-style: none;
}

.button {
  visibility:hidden;
  clip:rect(0 0 0 0);
  position: absolute;
  left: 9999px;
}

label {
  background-image: url("Images/buttonUnClicked.png");
  background-size: 100px;
  background-repeat: no-repeat;
  width: 100px;
  height: 100px;
  display: block;
}

.button:checked + label {
  background-image: url("Images/buttonClicked.png");
}

I made this demo for you on CodePen.

Upvotes: 1

Related Questions