␡
- Random Picture Rotation with JavaScript
- How the Rotating Images Code Works
- The Coding Plan
- Some Key JavaScript Concepts
- Detecting the Load Event
- Triggering the Function from the Load Event
- Generating Random Numbers
- Creating the Image Path
- DOM Scripting
- Assembling the Image Element
- Adding the Image Element to the Page
- Reviewing the Working Page
- Summary
Like this article? We recommend
Reviewing the Working Page
Reviewing the Working Page
If we load the page a few times, the images appear randomly, as shown in Figure 4.
Figure 4 Each time we load the page, one of the five images will be displayed.
Our complete page code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Random Picture Rotation - a JavaScript tutorial by Charles Wyke-Smith</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> body {font-family:verdana, sans-serif;} h1, p, div { width:500px; margin-left:auto; margin-right:auto; } h1 { border-top:3px solid #069; padding-top:10px; } div#display { border-bottom:2px solid #069; padding-bottom:10px; } </style> </head> <body> <script type="text/javascript"> //////////////////////////////////////////////////////////////////////// //Random Picture Rotation by Charles Wyke-Smith - http://www.scriptinwithajax.com // A script that loads a random picture each time the page is loaded // This script assumes your images are named pic1.jpg, pic2.jpg, etc. // Also assumes images in folder called images at same level as HTML doc // Set the picCount variable equal to the number of images to rotate // This script can be used freely if this message is kept intact window.onload = pickAPic; function pickAPic() { var randomNum; // a variable to hold the random number var picCount = 5; // the number of pictures to rotate randomNum = Math.floor(Math.random()*picCount)+1; var mySrc="images/pic"+randomNum+".jpg" var myImgEl = document.createElement("img"); myImgEl.setAttribute("src",mySrc); myImgEl.setAttribute("alt","my old car"); var theDiv = document.getElementById("display"); theDiv.appendChild(myImgEl); } </script> //////////////////////////////////////////////////////////////////////// <h1>My old car!</h1> <p><a href="random_images.html">show another random pic</a></p> <div id="display"></div> </body> </html>