-2

How do I go about spawning a specific image if a particular if/else statement is true?

I keep trying but the src just causes the image to stay on the page and not disappear when the if statement is false.

if (B == "k k"){

  //I want my image to appear through this if statement

  }else {

  //and a separate image to appear if this "else" is true
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
Herp Derp
  • 1
  • 2
  • You've shown an if/else ... but not what you're doing in each case ... so how can we possibly help? – Jaromanda X Oct 19 '18 at 23:43
  • Would you not just reference the image element and then set the src to the image? Please see the following https://stackoverflow.com/questions/1232793/javascript-set-img-src – slee423 Oct 19 '18 at 23:46

2 Answers2

0

You can conditionally show or hide an image by setting display: none; on it, example snippet below:

function toggleImage() {
  var img = document.querySelector('img');
  if (img.style.display === 'block') {
    img.style.display = 'none';
  } else {
    img.style.display = 'block';
  }
}
button {
  display: block;
  margin: 20px 0;
}
<button onclick="toggleImage()">toggle image</button>

<img src="https://source.unsplash.com/random/200x200" style="display: block;" />
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
0

add id to your image

  <img id="your-image-id" src="" alt="" >

you can set src on if statement

 var img = document.getElementById("your-image-id")

    if (B == "k k"){

   img.src ="linkto your image" 

  }else {

   img.src ="linkto your another image" 
}
hossein sedighian
  • 1,711
  • 1
  • 13
  • 16