How to display random text phrases from a given set using JavaScript code.
displaying random text on a web page using JavaScript, random text display using JavaScript, random text on a web page
Displaying random text on a web page using JavaScript - 2Go to Displaying random text on a web page using JavaScript - 2HTML & JavaScriptGo to HTML and JavaScript tips and tricksTips and tricksGo to web development Tips and tricksHomepage

Displaying random text on a web page using JavaScript - 2

Now that you know how to randomly display text, we'll see how we can display this text as a marquee (using the <marquee> tag) in Internet Explorer or make this text blink (using the <blink> tag in Netscape Communicator).

The first step is to make a browser detection script. Depending on the browser, we execute the appropriate document.write() method.

The browser detention script use the appName property of the navigator object.

<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());

if (navigator.appName == "Netscape")
   {
   document.write("<blink><font color='
   #FF0000'>" + r_text[i] + "</font></blink>");
   }
else
   {
   document.write("<marquee><font color='#FF0000'>" +
   r_text[i] + "</font></marquee>");
   }

//-->
</script>

We first put all the text strings as individual array elements. 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. We, thus, need a random number between 0 and 6.
The Math.random() method returns a floating point (decimal) number between 0.0 and 1.0. We multiply this with 7 to get numbers between 0.0 and 7.0 but that would still contain decimals. To get an integer we use the JavaScript Math.floor() method. This integer is then used as an index to retrieve the string from the r_text array.

The Result
Click on the refresh button to see another text string below.




AddThis Social Bookmark Button


Page contents: Learn how to display random text on a web page using JavaScript code that picks up one phrase from a set of phrases.

Page URL: http://www.webdevelopersnotes.com/tips/html/ displaying_random_text_on_a_web_page_using_javascript_2.php3



Join Mailing List


Feedback/Questions




50+ web hosting FAQs

Search engine for your website

Free software from Google - The Google Pack Collection

Create your own search engine
Search WebDevelopersNotes.com