12,895,062 members (62,278 online)
Tip/Trick
alternative version

#### Stats

12.4K views
Posted 4 Mar 2010

# How to show random Images, text, quotes on webpage using Javascript

, 4 Mar 2010 CPOL
 Rate this:
Hi, On many occations we want to display random, image, texts or stock-quotes on the web page. e.g. i was working on gallary that will show random images at every page refresh. In my solution i have written server side code to generate JavaScript Code in my page. Here i will explain only...
Hi,

On many occations we want to display random, image, texts or stock-quotes on the web page. e.g. i was working on gallary that will show random images at every page refresh. In my solution i have written server side code to generate JavaScript Code in my page.

Here i will explain only JavaScript code.

The idea is very simple, i have used Math.Random() function to get the random number, i have used array, that will contain the list of texts, image names etc.

1. First thing is that we should know how many elements (i.e. Texts, quotes, images) are there for selecting one from them. After this we need to add those into the array.

2. Now, we use length property in order to know how many elements are there in the array.

3. Math.Random gives values between 0 to 1. Now multiply this with array length, this it will be any value from 0 to arraylength (e.g. say array length is 5 then the number is somewhere between between 0 to 5).

4. But still this number is in decimal format so, it resulted in to "Undefined" array error, to solve this i have used math.floor so it resulted in to giving integer number.... this is our array index.

5. Now, assign this, to the src of image, or to label. to show the random image, or text

```//this is the array from which we want to get random message.
var randomText = new Array ("Hi", "Hello",
"How are you", "what are you doing", "what is the matter");

//variable i contains random value between 0 and 1
var i = Math.random();

//variable arrayLength contains the length of the array i.e. total number of message-strings, images etc.
var arrayLength=randomText.length;

//multiplying the randomly generated value with length of array will give the numbers from 0 to length of array
i=Math.floor(i*arrayLength);
document.getElementById("lblMessage").innerHTML = randomText[i];

//for showing random image
//document['picture'].src=randomText[i]
//here array contains the list of iamges```

## Share

 Software Developer (Junior) Excel Informatics, Pune India
Am Indrajeet T. Sutar. I am a web developer. I am working on .net technology. I have completed my Masters in Computers and Management (people call it as MCA, MBA etc.) Apart from programming i do photography (not regularly though), traveling and reading books.

## You may also be interested in...

 Pro

 First Prev Next
 My vote of 2 sujitnagri22-Apr-10 22:47 sujitnagri 22-Apr-10 22:47
 Last Visit: 31-Dec-99 18:00     Last Update: 28-Apr-17 19:43 Refresh 1