Recipe 6.5. Randomizing Text or Images


Problem

You need to display a different text block, image, or other type of content on a page every time it gets viewed.

Solution

Use JavaScript's Math.round( ) and Math.random( ) functions to select and print one random element from an array of content items that can be displayed on the page.

First, define the array of content items and variables that will define one random selection from the array in the <head> section of your web page:

 <script type="text/JavaScript" language="JavaScript"> <!-- randContent = new Array(); randContent[0] = "…item 0…"; randContent[1] = "…item 1…"; randContent[2] = "…item 2…"; randContent[3] = "…item 3…"; randContent[4] = "…item 4…"; var numb = randContent.length-1; var mathRandom = Math.random(); var mathRound = Math.round((mathRandom*numb)); var randDisplay = randContent[mathRound]; //--> </script> 

Then use JavaScript to print one element from the array by adding this code to the <body> of the page where you want the content to be displayed:

 <script type="text/JavaScript" language="JavaScript"> <!-- document.write(randDisplay); //--> </script> 

Discussion

Content items listed in the randContent array can be almost anything you want: testimonials from your best customers, sale items from your online store, work samples from your portfolio, Flash movies, or even advertisements and sponsor logos.

The variable mathRound defines the element in the array that will be displayed.

Remember, JavaScript array elements are numbered starting at zero.


To get that value, the script generates a random number between 0.0 and 1.0 with the Math.random( ) function, and then multiplies that number by the number of elements in the arrayless oneto ensure that the product of Math.round((mathRandom*numb)) never exceeds the last element number in the array, which in this example is 4.

You also can randomize an array with a PHP script using the built-in shuffle( ) function. After passing the array to the function, echo element number 0 on the page:

 $randContent[0] = "…item 0…"; $randContent[1] = "…item 1…"; $randContent[2] = "…item 2…"; $randContent[3] = "…item 3…"; $randContent[4] = "…item 4…"; shuffle($randContent); echo $randContent[0]; 



Web Site Cookbook.
Web Site Cookbook: Solutions & Examples for Building and Administering Your Web Site (Cookbooks (OReilly))
ISBN: 0596101090
EAN: 2147483647
Year: N/A
Pages: 144
Authors: Doug Addison

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net