Website Design Edmonton       Website Design Feedback       Website Design Sitemap     Contact Website Design Company
Website Designers R Us - Home
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

Website Designer R Us is the right company to get your job done professionally and cost effectively. We've seen the good, the bad, and the ugly, and we are here to help you by recommending the services that match your needs based on our knowledge of other website designers and web design companies whom can perform the type work you are needing.
 Home          ::             About Us          ::             Support            ::             Services            ::             Link Partners          ::             Contact

Copyright © 2006-2011 Website Designers R Us, a DOT Specialist Company. All rights reserved.