I have a web page that contains a bunch of advertisements. What I need to do it randomly shuffle these images each time the page is refreshed. I cannot have any repeating ads.
Here is the code I have now.... it repeats images.

<html>
     <head>
          <script type="text/javascript">
               function random()
              {
                    images = new Array(3);
                    images[0] = "<a href='http://www.xxxxxxxxxxxxx.ca' target='_blank'><img src='xxxxxxxx.jpg' alt='' /></a>";
                    images[1] = "<a href='xxxxxxxx' target='_blank'><img src='xxxxxxx.jpg' alt='' /></a>";
                    images[2] = "<a href='xxxxxxxx' target='_blank'><img src='xxxxxxxx.jpg' alt='' />";
                   for(var i = 0; i < images.length; i++)
                  {
                       index = Math.floor(Math.random() * images.length);
                      document.write(images[index]);
                 }
           }
         </script>
     </head>
     <body>
           <script type="text/javascript">
                random();
          </script>
     </body>
</html>

I would like to keep the code as simple as possible.

// don't use new Array(3), just use []
var i, images = [];

// use push, don't manually assign the index
images.push("somelink1");
images.push("somelink2");

// shuffle the array
images.sort(function ()
{
    return 0.5 - Math.random();
});

for(var i = 0; i < images.length; i++)
{
    document.write(images[index]);
}

I made the changes sugguested but I am getting an error which says that index is undefined. How do I fix this? Sorry I am new to javascript.

whoops, change document.write(images[index]); to document.write(images[i]);

of nevermind I changed index to i and it seems to work.
Thank you for your help.

sorry but there is a new problem...
it doesn't seem to be display all of the images. I have 11 and it's only displaying 9 of them. Do you know why this is?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.