Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Random Image Generator - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Functions

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Random Image Generator - JavaScript(JS)

Web content that varies randomly adds dynamic, interesting effects to a page.

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"

 

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 9.7: RandomPicture.html -->

 

    <!-- Random image generation using Math.random. -->

 

    <html xmlns = "http://www.w3.org/1999/xhtml">

 

    <head>

 

    <title>Random Image Generator</title>

 

      <script type = "text/javascript">

      <!--

 

      document.write ( "<img src = \"" +

      Math.floor( 1 + Math.random() * 7 ) +  ".gif\" />" );

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <p>Click Refresh (or Reload) to run the script again</p>

 

      </body>

 

</html>


Fig. 9.7 | Random image generation using Math.random.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.