| Random text display using JavaScript one |
Random text display is very similar to displaying images randomly.
-
Store the text strings in an array
-
Using the Math.random() method to obtain a random value
-
Displaying the text using document.write() method
Storing text strings in an array
var r_text = new Array ();
r_text[0] = "All the leaves are brown";
r_text[1] = "And the sky is grey";
r_text[2] = "I've been for a walk";
r_text[3] = "On a winter's day";
r_text[4] = "I'd be safe and warm";
r_text[5] = "If I was in L.A.";
r_text[6] = "California dreaming, On such a winter's day";
Remember, JavaScript arrays are zero indexed (the first element of an array in JavaScript has an index of 0). Our array r_text consists of seven elements. The Math.random() method returns a value between 0 and 1. We have to convert this value to an integer between 0 to 6 so that it can be used as an index to retrieve the string from the r_text array. We store the final value in a variable i.
Generating a random number
var i = Math.round(6*Math.random());
Displaying the text
The final step is to display the text through document.write() method.
document.write(r_text[i]);
We now place all this code between <SCRIPT>-</SCRIPT> tags.
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--
var r_text = new Array ();
r_text[0] = "All the leaves are brown";
r_text[1] = "And the sky is grey";
r_text[2] = "I've been for a walk";
r_text[3] = "On a winter's day";
r_text[4] = "I'd be safe and warm";
r_text[5] = "If I was in L.A.";
r_text[6] = "California dreaming, On such a winter's day";
var i = Math.round(6*Math.random());
document.write(r_text[i]);
//-->
</SCRIPT>
|
| Return to Listing |