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.

Tip

Remember, JavaScript array elements are numbered ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.