Anez
Anez

Reputation: 1

Table in javascript with different images

I am trying to build a 2*2 table of different images using javascript so that no two pictures inserted are duplicates. I am new to javascript so please help me with the following code.

I have written the diffImage function to select random images, but it displays duplicate images. I want the page to display an image only once, and in a different cell every time the page is loaded.

<html>
  <head>
   <script language=Javascript>
       function diffImage() {
          image = new Array("ball.gif","bench.gif","banner.gif", wall.gif");
          whichImage = Math.floor(Math.random()*image.length);
          document.write('<image SRC="' +image[whichImage]+ '">');
       }
   </script>
</head>

<body>
  <table id="newtable"/>
   <tr>
    <td>
      <script language="Javascript"> diffImage();</script>
    </td>
    <td>
      <script language="Javascript"> diffImage();</script>
    </td>
 </tr>
 <tr>
    <td>
      <script language="Javascript"> diffImage();</script>
   </td>
   <td>
     <script language="Javascript"> diffImage();</script>
  </td>
 </tr>
</table>

Upvotes: 0

Views: 468

Answers (3)

w31rd
w31rd

Reputation: 1

change the function calls to diffimage()

Upvotes: 0

Techboy6601
Techboy6601

Reputation: 120

Check where you defined the image array. You forgot to put quotation marks on wall.gif.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Try this:

imagelist = ["ball.gif","bench.gif","banner.gif","wall.gif"];
function diffimage() {
    whichImage = Math.floor(Math.random()*imagelist.length);
    document.write('<img src="'+imagelist[whichImage]+'" />');
    imagelist.splice(whichImage,1);
}

This will remove the selected image from the list, so you won't get duplicates.

(Side-note: the probability of getting no duplicates with your current code is 3/32, or about 9%)

Upvotes: 2

Related Questions