Skip to content
Advertisement

JS Set background image of span

JS:

function getItem() {
  var rand = Math.floor((Math.random() * 110) + 1);
  Weapon = "Opening..."
  document.getElementById("Weapon").innerHTML = Weapon;

  if (rand < 3) {
      document.getElementById("Weapon").innerHTML = "Item Type One";
  } else if (rand > 2 && rand < 5) {
      document.getElementById("Weapon").innerHTML = "Item Type Two";
  }
  // Continues onward etc...
}

HTML:

<button onclick="getItem()">Get Item</button>
<span id="image"><!-- Display an image here? --></span>
You Unboxed: <span id="Weapon">Nothing</span>

I was wondering if it would be possible to also set the source of an image in this HTML from my Javascript code. So if I get “Item One” it will display that image in my HTML?

Advertisement

Answer

You just need to create an array containing the paths to your images such as

var images = ["image1.png", "image2.png"]

Then get a reference to your image element, then set its source to the image in the array accordingly

myImage.src = images[0] for example

Edit:

So you said you have an array of images like this

var images = ["stub.png", "Other.png"];

I see that you are using a <span> to display your images. So you need to get a reference to that <span> element.

var myImage = document.getElementById("weapon");

Since you are using a <span> element to display your image, not a <img>, so to show your image, you do this

myImage.style.backroundImage = url(images[n]); with n being the image index corresponding to your if/else. You should use <img> to display your image instead.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement