Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

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

2.00/5 (1 vote)
5 Mar 2010CPOL1 min read 1  
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)