|
|
Random text display using JavaScript - 1This little JavaScript tip involves randomly displaying a text string from a list. And this is how we shall be going about it:
Creating the array that stores the text stringsvar 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. We, thus, need an integer between 0 and 6. Generating a random numbervar i = Math.random(); The variable i now contains a floating point (decimal) number between 0 and 1. We have to convert it 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. i = 7 * i; i = Math.floor(i); We multiply the random floating point number (whose value is between 0.0 and 1.0) by 7 so that we get a number (again a floating point) that ranges from 0.0 to 7.0. The Math.floor() is used to round down this number. Thus, 0.345... would result in 0 and 6.893.. would be floored to 6. The above three JavaScript statements can actually be combined into one: var i = Math.floor(7*Math.random()) Displaying the textThe 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> You can also pack all this code in an external JavaScript file that is called from your web page. I would suggest that, unless its absolutely necessary, you should segregate all JavaScript code into an external file. This way you need to maintain only one file. The Result Note: I've put the text in red color so that i stands out - this is not required. When can you use this nice tip?In the past, I have displayed a random quote or a randomly selected a testimonial on the web page. And this is how I go about it.
Page contents: Discussion on how to display randomly selected text on a web page using JavaScript code.
Page URL: http://www.webdevelopersnotes.com/tips/html/ random_text_display_using_javascript_1.php3
|
|