Search code examples
javascripthtmlcssif-statementprompt

Picture appears after a choice from prompt has been made w/ JS


After the user has entered in an appropriate choice, I need to use a conditional statement that compares the input to my choices, and then render an image on the web page. I know somehow I have to use the CSS display, and possibly a if/then statement but I'm not entirely sure how or where. So far, I have this in my javascript. I'm not sure what I should use so that if the user inputs 'red' that a picture would appear (it's going to be Hogwarts related). Any tips in the right direction?

function myFunction() {
    var text;
  var favColor = prompt("What color appeals most to you out of red, green, blue, or yellow?", "Let the game begin");
  switch(favColor.toLowerCase()) {
    case "blue":
      text = "Sounds like you like to think";
      break;
    case "red":
      text = "Feeling bold?";
      break;
    case "green":
      text = "Really? Interesting choice";
      break;
      case "yellow":
        text = "How very clever of you!"
          break;
    default:
      text = "C'mon! Pick one!";
  }
  document.getElementById("demo").innerHTML = text;
}

Solution

  • You can add <img id="my-image" /> element on your page and change image src attribute based on user answer:

    var text;
    var src;
    var favColor = prompt("What color appeals most to you out of red, green, blue, or yellow?", "Let the game begin");
    switch(favColor.toLowerCase()) {
      case "blue":
        text = "Sounds like you like to think";
        src = 'blue_img.jpg';
        break;
      case "red":
        text = "Feeling bold?";
        src = 'red_img.jpg';
        break;
      case "green":
        text = "Really? Interesting choice";
        src = 'green_img.jpg';
        break;
        case "yellow":
        text = "How very clever of you!"
        src = 'yellow_img.jpg';
            break;
      default:
        text = "C'mon! Pick one!";
    }
    document.getElementById("demo").innerHTML = text;
    if( src ){
      document.getElementById( 'my-image' ).src = src;
    }
    

    It's better than make 4 hidden images which be displayed by display:block because browser downloads even hidden images.