Display Random Images with JavaScript

Images @ Painted Pixels

This is a simple way to display images on your web page using PHP. Each time the page is refreshed, the script will choose one image from a list of images to display on your page.

Step One

Create your web page as normal but save it with a php extension, for example, randomimage.php.

Step Two

Create a directory for your images and upload your images into that directory.

Step Three

Copy this code and paste it into your page where you want the images to be displayed.

<script language="JavaScript" type="text/javascript">
// Random Image Script by www.paintedpixels.com
var url = "www.yoursite.com/randomimage/images/";

var imageArray = new Array();

imageArray[0] = "image1.jpg";
imageArray[1] = "image2.jpg";
imageArray[2] = "image3.jpg";
imageArray[3] = "image4.jpg";

var randImg=Math.floor(Math.random()*(imageArray.length));
var imgurl = "http://" + url + imageArray[randImg];
document.write('<img src="' + imgurl + '">');
< /script>

What does it mean?

var url = "www.yoursite.com/randomimage/images/";

This is the url of your web page. Change it to reflect your site structure. Do not put http://

var imageArray = new Array();

This sets up the JavaScript array.

imageArray[0] = "image1.jpg";
imageArray[1] = "image2.jpg";
imageArray[2] = "image3.jpg";
imageArray[3] = "image4.jpg";

These are your images. Replace "image1.jpg";, "image2.jpg"; etc with the name of your images.

If you wish to add more than four images continue the pattern like this:

imageArray[4] = "image5.jpg";
imageArray[5] = "image6.jpg";
imageArray[6] = "image7.jpg";

Notice how the format stays the same. Only the number in square brackets increases by 1 for each image.

var randImg=Math.floor(Math.random()*(imageArray.length));
var imgurl = "http://" + url + imageArray[randImg];
document.write('<img src="' + imgurl + '">');

These three lines choose a random image from the array, works out the full url to your image and prints the image to your web page. Do not change these three lines.

You are now finished!

Your page should look similar to this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html>
< head>
<title>Random Image</title>
< meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
< /head>

<body>
<h2 align="center">My Images</h2>

<script language="JavaScript" type="text/javascript">
// Random Image Script by www.paintedpixels.com
var url = "www.yoursite.com/randomimage/images/";

var imageArray = new Array();

imageArray[0] = "image1.jpg";
imageArray[1] = "image2.jpg";
imageArray[2] = "image3.jpg";
imageArray[3] = "image4.jpg";

var randImg=Math.floor(Math.random()*(imageArray.length));
var imgurl = "http://" + url + imageArray[randImg];
document.write('<img src="' + imgurl + '">');
< /script>

</body>
< /html>

Now when you refresh the page, a different image will be displayed. Enjoy!