-1

Is there a way to have an image appear when a certain phrase is typed into an input using an if statement? This is my code

<script type="text/javascript">

    document.getElementById("button").onclick=function() {

        var ask=document.getElementById("ask").value.toLowerCase(); ;
        if (ask =="how tall are the pyramids") {

            document.getElementById("spanId").innerHTML = "146.5 meters";

        } else if (ask== "how tall is the gateway arch") {

            document.getElementById("spanId").innerHTML = "630 feet";

        }
Max R
  • 109
  • 4
  • 16

3 Answers3

1

All you need to do is set the image's path - this will load the image off the web server:

<script type="text/javascript">

document.getElementById("button").onclick=function() {

    var imageSrc = "";

    var ask=document.getElementById("ask").value.toLowerCase(); ;
    if (ask =="how tall are the pyramids") {
        document.getElementById("spanId").innerHTML = "146.5 meters";
        imageSrc = "pyramids.jpg";
    } else if (ask== "how tall is the gateway arch") {
        document.getElementById("spanId").innerHTML = "630 feet";
        imageSrc = "arch.jpg";
    }

    // update the image
    document.getElementById("image_placeholder").src = imageSrc;

You can also "preload" all the images so that the UI feels snappier. To do so you can create Image objects in a loop and set their .src to the images' paths. Once they are loaded the image flip will be immediate.

YePhIcK
  • 5,816
  • 2
  • 27
  • 52
1

You can try like -

document.getElementById("spanId").innerHTML = "<img src='path/arch.jpg'>";

or

document.getElementById("spanId").innerHTML = "<p>630 feet</p><img src='path/gatewayarch.jpg'>";
Roy
  • 69
  • 4
0

Yes, there are some ways of achieving what you want, e.g:

if (ask =="how tall are the pyramids") {
  document.getElementById("spanId").innerHTML = "146.5 meters <img src='yourimg.png'>";

Or:

var img = document.createElement('img');

if (ask =="how tall are the pyramids") {
  var span = document.getElementById("spanId");
  span.innerHTML = "146.5 meters";
  img.src = 'yourimg.png';
  span.appendChild(img);

Or, if you don't have the image located physically in your webserver, you can do:

if (ask =="how tall are the pyramids") {
  var base64 = 'YOUR_IMAGE_BASE64_STRING';
  document.getElementById("spanId").innerHTML = '146.5 meters <img src="data:image/jpg;base64,' + base64 + '" />';

You can convert any image you have to a base64 string with this converter.

Buzinas
  • 11,597
  • 2
  • 36
  • 58