0

I'm trying to use a button click to randomly display an image and text. My current code works to randomise the name display, but the image comes up broken. What is the correct syntax for having the image from random display div id=target?

<input type="button" id="btnSearch" value="Randomize" onclick="GetValue();" />
<br>
<img id="target" src="/img/test.png">
<p id="message" > test </p>

<script>
const btn = document.querySelector("#btnSearch");

function GetValue()
{
    var quotes        = [
            { 
    name: "Roller Coaster",
    img: "/img/emojibase/rollercoaster.png",
  },
            { 
    name: "Rooster",
    img: "/img/emojibase/rooster.png",
  },
            { 
    name: "Rose",
    img: "/img/emojibase/rose.png",
  }
    ];   

    var random = quotes[Math.floor(Math.random() * quotes.length)];

    document.getElementById("message").innerHTML = random.name;
    document.getElementById("target").innerHTML = random.img;
}

btn.addEventListener("click", () => {
    GetValue();
});
</script>

1 Answer 1

4

Instead of the innerHTML you should use the src attribute of the image element.

Change:

document.getElementById("target").innerHTML = random.img;

To:

document.getElementById("target").src = random.img;

<input type="button" id="btnSearch" value="Randomize" onclick="GetValue();" />
<br>
<img id="target" src="/img/test.png">
<p id="message" > test </p>

<script>
  const btn = document.querySelector("#btnSearch");

  function GetValue()
  {
      var quotes        = [
              { 
      name: "Roller Coaster",
      img: "/img/emojibase/rollercoaster.png",
    },
              { 
      name: "Rooster",
      img: "/img/emojibase/rooster.png",
    },
              { 
      name: "Rose",
      img: "/img/emojibase/rose.png",
    }
      ];   

      var random = quotes[Math.floor(Math.random() * quotes.length)];

      document.getElementById("message").innerHTML = random.name;
      document.getElementById("target").src = random.img;
  }

  btn.addEventListener("click", () => {
      GetValue();
  });
</script>

Sign up to request clarification or add additional context in comments.

Comments

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.