|
|
Displaying random text on a web page using JavaScript - 2Now 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 Result
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
|
|