Skip to content

JavaScript Rotating Images Tutorial

Introduction

Swapping new images into an established layout is one trick that can keep a site design fresh. Some examples:

There are several different techniques for accomplishing this effect. A server-side program is the best approach, because you can automatically pull files from a whole directory (eliminating the need to modify code), and it will work even if a user has JavaScript disabled.

Unfortunately, not everyone has access to a host that supports server-side scripting. That’s okay, because the same thing can be accomplished with client-side code in JavaScript. I’ll show you how, with three JavaScript functions of varying levels of ease and functionality. First, gather two or more images that are the same size. Then read on…

Setup

Click here to see the script run. Reload a few times (you may need to right-click and choose ‘reload’). Then view the page source.

This HTML is simple (and valid)!

<body onload=“selectPicBasic()”>
<img id=“pic” src=“rose1.jpg” alt=“a rose of any name” style=“width:200px;height:200px;” />
</body>

The onload event of the body tag calls the rotating image function. The image tag should be positioned on the page as normal. The width and height are the same as the width and height of the images.

Basic Function

This is the most basic and straightforward implementation. Name your images incremental filenames, like ‘rose1.jpg’, ‘rose2.jpg’, etc. Then use the following function to load them dynamically:

function selectPicBasic() {
  // generate a random number between 1 and 3
  var randomNum = Math.floor(Math.random() * 3)+1;
  // build the filename string including the random num
  var filename = “rose” + randomNum + “.jpg”;
  // set the src of the image equal to the filename
  document.getElementById(“pic”).src = filename;
}

This function generates a random number from 1 to 3 (to refer to images ‘rose1.jpg’, ‘rose2.jpg’, and ‘rose3.jpg’). It builds the filename string piece by piece, using the concatenation operator (+). Finally, it gets a pointer to the image element in the body of the document via the tag’s id attribute, and sets the src attribute of the image element to the new, randomly generated filename.

This works for simple cases, but it does have some serious drawbacks; you need to modify two of the three lines of the function to update it, and it only supports filenames that follow the roseX.jpg pattern.

Better Function

This function expands the previous one and fixes those issues.

function selectPicBetter() {
  // create an array of all possible images
  var picArray = new Array(‘rose1.jpg’,‘rose2.jpg’,‘rose3.jpg’);
  // select a random num between 0 and length of the array
  var randomNum = Math.floor(Math.random() * picArray.length);
  // assign a random array entry to the src of the image
  document.getElementById(“pic”).src = picArray[randomNum];
}

This function uses an array to store a set of filenames. It generates a random number between zero (the first index of the array) and the length of the array, and sets the src attribute of the image to that entry in the array. To add more files to the rotation, just add them to the array.

Cowboy Function

This is the version written just because it can be. It’s a rewrite of the basic function, in one line.

function selectPicCowboy() {
  document.getElementById(“pic”).src=“rose”+(Math.floor(Math.random()*3)+1)+“.jpg”;
}

Don’t do this. Unless you’re a cowboy.

Conclusion

If you’re limited to client-side coding, the selectPicBetter() function is a decent, quick, and clear approach to incorporating rotating images into your site.

Please learn from this code, but if you use it, I appreciate attribution!

Related posts