Random Image Swap with Prototype

Tagged with Prototype Javascript

Language: HTML / XHTML

A simple example using Prototype to change the banner image upon refresh. This version inserts the banner into the page and displays a default one when scripts are disabled.

View as text

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
 <head>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  <title>Test</title>
   <script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js">
   </script> 
 </head>
 <body id="mypage">
   
   <div id="banner">
     <noscript>
       <img src="http://www.uwec.edu/images/experience5_1.jpg" alt="one"/>
     </noscript>
   </div>
   
   <script type="text/javascript" charset="utf-8">
        
    var images = [["http://www.uwec.edu/images/experience5_1.jpg", "one"],
                  ["http://www.uwec.edu/images/experience4_1.jpg", "two"],
                  ["http://www.uwec.edu/images/experience3_1.jpg", "three"],
                  ["http://www.uwec.edu/images/experience2_1.jpg", "four"]
                  ]
    
    var randomnumber = Math.floor(Math.random()*(images.length)) 

    var banner_div = $("banner");
    var image_src = images[randomnumber][0];
    var image_alt = images[randomnumber][1];
    banner_div.innerHTML = '<img id="banner" src="' 
          + image_src + '" alt="' + image_alt + '" />';
    
   </script>

  
 </body>
 
</html>
Original snippet written by Brian Hogan
Last updated at 21:25 PM on Dec 12, 2008 by Brian Hogan

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.