Random Image Display with JavaScript
This programming challenge is from a Lynda.com instructional video, featuring Dori Smith, which I studied/practiced last summer but once again spring 2009. I do not mean to just re-post the wonderful Lynda.com code, but rather add instructional value to it by way of clearer variable names and explanatory comments. The end result itself is not terribly sexy, but I liked the algorithm construction process.
I post these self-instructional challenges for a few reasons. One is to demonstrate my programming learning, experience, and progression. Another reason is to make sure my code and solutions are indexed by search engines, so that other beginning programmers may get help if they need it. Finally, self-instructional challenges are interesting and different than academic challenges because I sought, discovered, and performed them on my own volition without anyone else telling me to do so. I did it because I wanted to learn and practice.
Challenge: Create a simple script to randomly pull and display an image on a web page.
The HTML solution:
<html> <head> <title>NASA Astronomy Picture of the Day Gallery</title> <script type="text/javascript" src="script.js"></script> <link rel="stylesheet" rev="stylesheet" href="styles.css" /> </head> <body> <img src="images/spacer.gif" id="aRandomPicture" alt="a Random image" /> </body> </html>
The JavaScript solution:
// run randomPic function whenever page loads
window.onload = randomPic;
// setup array of image files
var myPics = new Array("images/1.jpg", "images/2.jpg", "images/3.jpg", "images/4.jpg", "images/5.jpg", "images/6.jpg", "images/7.jpg", "images8.jpg");
function randomPic() {
// generate random number based on image quantity
randomNumber = Math.floor((Math.random() * myPics.length));
// set the image src attribute to a random pic in the image array
document.getElementById("aRandomPicture").src = myPics[randomNumber];
}
It’s as simple as that!










