Random Text and Image Display with JavaScript, Part 2
As promised, here is the second part of my three part Javascript Tutorial.
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.
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.<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.floor(7*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>
About the Author Kyle Reddoch is a Web Development Expert and Internet Guru located in Amarillo, TX. To learn more about him, you can visit his site at KyleReddoch.com.
