There are times when it is helpful to use a script to select a random value. The following script can be used to select a random piece of content from a predefined array. You might like to use it to add random quotes or tips, or you could use it to rotate advertisements or images. The script contains a function called randomContent() that includes the content that will be selected at random.
The content is added to an array called arrContent and the array contains the data you want to appear
randomly:
A variable called i is then set to a random value between 0 and the number of items in the array. In order to generate this random number, you need to call two methods of the Math object. The random() methodgenerates a random number between 0 and 1 and this is multiplied by the number of elements in the array. The number is then rounded to the nearest integer (whole number) equal to or less than the number generated using the floor() method.
The content is added to an array called arrContent and the array contains the data you want to appear
randomly:
Code:
<script language=”JavaScript”>
function randomContent(){
var arrContent=new Array()
arrContent[0]=’This is the first message.’
arrContent[1]=’This is the second message.’
arrContent[2]=’This is the third message.’
arrContent[3]=’This is the fourth message.’
arrContent[4]=’This is the fifth message.’
A variable called i is then set to a random value between 0 and the number of items in the array. In order to generate this random number, you need to call two methods of the Math object. The random() methodgenerates a random number between 0 and 1 and this is multiplied by the number of elements in the array. The number is then rounded to the nearest integer (whole number) equal to or less than the number generated using the floor() method.
Comment