Issue with image generator in html/javascript

93 Views Asked by At

I have looked around trying to find a solution for my problem but I can't figure out where my code went wrong. I broke up the code into two files on my website so I split them up into html and javascript.

HTML:

<html>
<!-- 
-->
<script type="text/javascript" src="external_javascript.js"></script>

<form name="imageForm">
  <table border=3>
  <tr>
    <td>
      <input onclick="displayImage();" type=button value="Display Random Image">
    </td>
  </tr>
  <tr>
    <td>
      <img src="blank.jpg" name="canvas" />
    </td>
  </tr>
  </table>
</form>
</html>

Javascript:

<html>

<script> 
//create an array named imagesArray that contains the seven image file names
//dog.jpg, fox.jpg, mouse.jpg, alligator.jpg, fish.jpg, parrot.jpg and cat.jpg

var imagesArray = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg"];


//create a function named displayImage
//it should not have any values passed into it

function displayImage(){

    //the first statement should generate a random number in the range 0 to 6 (the subscript values of the image file names in the imagesArray)
    var num = Math.floor(Math.random() * (imagesArray.length+1)); // 0...6
    //the second statement display the random image from the imagesArray array in the canvas image using the random number as the subscript value
    document.canvas.src = imagesArray[num];

}

//remember the subscript values of the array are 0 to 6 (seven elements) zero based array
//you will have to subtract 1 from the random number generated to account for the zero based array
</script>

</html>

I also have uploaded to my website manager images that go from a.jpg to z.jpg Thanks in advance!

1

There are 1 best solutions below

0
On

Your .js-file should look like this:

var imagesArray = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg", "g.jpg"];

//create a function named displayImage
//it should not have any values passed into it

function displayImage(){

    //the first statement should generate a random number in the range 0 to 6 (the subscript values of the image file names in the imagesArray)
    var num = Math.floor(Math.random() * (imagesArray.length+1)); // 0...6
    //the second statement display the random image from the imagesArray array in the canvas image using the random number as the subscript value
    document.canvas.src = imagesArray[num];
}

<html> and <script> are tags of HTML markup.