Javascript: Random Image Generator

Javascript: Random Image Generator

I wrote a tutorial on generating random links with javascript some months ago. Recently, a person requested to show how to show this method but with images. This is why I’m writing this tutorial about how to create a random image generator.

The first thing you need to do is create an array with the URLs of the images you’re going to use. There are two common ways to do this, as you saw on the random link tutorial.

The condensed array:

<script>
// Condensed Array

var randomImage = new Array("http://url.com/image01.jpg", "http://url.com/image02.jpg", "http://url.com/image03.jpg");
</script>

Or the regular array:

<script>
// Regular Array

function getRandomImage() {

var randomImage = new Array(); 
randomImage[0] = "http://url.com/image01.jpg"; 
randomImage[1] = "http://url.com/image02.jpg"; 
randomImage[2] = "http://url.com/image03.jpg";
} 
</script>

You can use any of these two methods. The next step is to create the function that will generate the images using a native random method.

<script>
var number = Math.floor(Math.random()*randomImage.length);
document.write('<img src="'+randomImage[number]+'" />');
}
</script>

And that’s it! All that’s left for you to do is to combine all the code (showed below), which would display the image and every time you refresh the page, a random image from your array will appear.

DEMO

Here’s the complete code:

<script>
<!--
// Random Image Generator
// Array with random image links is created. You can add as many links as you want/need.

// Regular Array

var randomImage = new Array();

randomImage[0] = "http://url.com/image01.jpg";
randomImage[1] = "http://url.com/image02.jpg";
randomImage[2] = "http://url.com/image03.jpg";
randomImage[3] = "http://url.com/image04.jpg";
randomImage[4] = "http://url.com/image05.jpg";

function getRandomImage() { 
var number = Math.floor(Math.random()*randomImage.length);
document.write('<img src="'+randomImage[number]+'" />');
}
getRandomImage()
//-->
</script>

 

If you have any questions, don’t hesitate to leave a comment.

 

5 thoughts on “Javascript: Random Image Generator”

  1. I was actually going to ask about this on the Byte Sized forum the other day, then I forgot. So this is SUPER helpful as I don’t want to install a plugin for something code can do.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top