MiLisCer
MiLisCer

Reputation: 23

Javascript Random number display

I have the following code to rotate banners on a forum, I have expanded the URLs for the purpose of posting the code here, so everyone can see how it works and not just the short urls.

As you can see each time the page is refreshed my script starts back with the first image.

I am looking to make the script start with a random number between 0-6 (or whatever number I set) so that it does not always appear with the same banner each page load.

I am happy with the timed rotations and do not want to change this.

<script language="JavaScript1.2">
  var howOften = 30;               // number often in seconds to rotate
  var current = 0;                 // start the counter at 0
  var ns6 = document.getElementById&&!document.all; // detect netscape 6

  // place your images, text, etc in the array elements here
  var items = new Array();
  items[0]="<a href=http://www.hornady.com/ ><img alt='image0 (9K)' src='http://wwww.bulletdrop.co.uk/ads/png2.png' width='60%' /></a>";           
  items[1]="<a href='http://www.blackfoxoptics.co.uk/'><img alt='image1 (9K)' src='http://wwww.bulletdrop.co.uk/ads/png1.png' width='60%'  /></a>"; 
  items[2]="<a href='http://epgroupuk.com/'><img alt='image2 (9K)' src='http://wwww.bulletdrop.co.uk/ads/png3.png' width='60%'  /></a>";  
  items[3]="<a href='https://barrett.net/'><img alt='image3 (9K)' src='http://wwww.bulletdrop.co.uk/ads/png4.png' width='60%'  /></a>";    
  items[4]="<a href='link.htm'><img alt='image4 (9K)' src='http://wwww.bulletdrop.co.uk/ads/png5.png' height='120' width='600' border='0'/></a>"; 
  items[5]="<a href='link.htm'><img alt='image5 (18K)' src='/Images/image5.jpg' height='300' width='300' border='0' /></a>";  

  function rotater() {
    document.getElementById("placeholder").innerHTML = items[current];
    current = (current == items.length-1) ? 0 : current + 1;
    setTimeout("rotater()", howOften*1000);
  }

  function rotater() {
    if (document.layers) {
      document.placeholderlayer.document.write(items[current]);
      document.placeholderlayer.document.close();
    }
    if (ns6) document.getElementById("placeholderdiv").innerHTML = items[current]

   if (document.all) placeholderdiv.innerHTML = items[current];

   current = (current == items.length-1) ? 0 : current + 1; // increment or reset
   setTimeout("rotater()", howOften*1000);
 }
 window.onload = rotater;
 //-->

Sorry cannot get code to display correct.

I would then call the script using:

 <layer  id="placeholderlayer" ></layer><div align="center"    
 id="placeholderdiv"></div>

Hopefully someone can help with this?

Mike

Upvotes: 2

Views: 65

Answers (1)

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

You can calculate the current like this:

var max = 5;
var min = 0;
current = Math.floor(Math.random()*(max-min+1)+min);

And then you can use the current.

Upvotes: 1

Related Questions