Monday, February 8, 2010

Randomize Image Display using Javascript

When you reach the location of your HTML that you need to display an randomized image, you can use these codes as a reference:


<script language="javascript">
<!--
var rn = "";
rn = Math.floor(Math.random()*11);
if (rn == "0") {document.write("<img src=\"/img/pic0.jpg\">");}
if (rn == "1") {document.write("<img src=\"/img/pic1.jpg\">");}
if (rn == "2") {document.write("<img src=\"/img/pic2.jpg\">");}
if (rn == "3") {document.write("<img src=\"/img/pic3.jpg\">");}
if (rn == "4") {document.write("<img src=\"/img/pic4.jpg\">");}
if (rn == "5") {document.write("<img src=\"/img/pic5.jpg\">");}
if (rn == "6") {document.write("<img src=\"/img/pic6.jpg\">");}
if (rn == "7") {document.write("<img src=\"/img/pic7.jpg\">");}
if (rn == "8") {document.write("<img src=\"/img/pic8.jpg\">");}
if (rn == "9") {document.write("<img src=\"/img/pic9.jpg\">");}
if (rn == "10") {document.write("<img src=\"/img/pic10.jpg\">");}
// -->


Note that you need to use the Math.random() function to generate random numbers from 0 to 1 (exclusive). Then you need to multiply the random fraction number to the maximum random number you want plus 1. You then use Math.floor() to round it up to the closest integer number.

Here we go!

No comments:

Post a Comment