Example: Random Image Generator
Web content that varies randomly adds dynamic, interesting effects to a page. In the next example, we build a random image generator, a script that displays a randomly selected image every time the page that contains the script is loaded.
For the script in Fig. 9.7 to function properly, the directory containing the file RandomPicture.html must also contain seven images with integer filenames (i.e., 1.gif, 2.gif, …, 7.gif). The web page containing this script displays one of these seven images, selected at random, each time the page loads.
Lines 12–13 randomly select an image to display on a web page. This docu-ment.write statement creates an image tag in the web page with the src attribute set to a random integer from 1 to 7, concatenated with ".gif". Thus, the script dynamically sets the source of the image tag to the name of one of the image files in the current directory.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!-- Fig. 9.7: RandomPicture.html -->
<!-- Random image generation using Math.random. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<title>Random Image Generator</title>
document.write ( "<img src = \"" +
Math.floor( 1 + Math.random() * 7 ) + ".gif\" />" );
<p>Click Refresh (or Reload) to run the script again</p>
Fig. 9.7 | Random image generation using Math.random.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.