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
var randomText = new Array ("Hi", "Hello",
"How are you", "what are you doing", "what is the matter");
var i = Math.random();
var arrayLength=randomText.length;
i=Math.floor(i*arrayLength);
document.getElementById("lblMessage").innerHTML = randomText[i];