Random image generator in JavaScript

This section will cover the process of generating random images dynamically on a webpage using JavaScript. We will implement a random image generator by combining JavaScript and HTML source code. To begin, we need to set up an array that will store the URLs of the images that will appear on the webpage.

The idea of a random image generator is commonly employed in advertising. Images that appear on a website in a random manner are typically preloaded in a database or an array. These images are presented to the user at regular intervals or can be altered with a click. Alternatively, it is possible to specify a direct web link for an image.

Two distinct techniques will be explored for creating a random image generator with JavaScript. The following sections detail both methods:

Approach 1

In this method, images will appear randomly on the webpage at regular intervals when a button is clicked once. The setInterval function in JavaScript will be utilized to establish a timer for displaying the images.

In the following instance, the image's initial dimensions were utilized. It is also possible to specify the dimensions for each image that will be shown. To do this, proceed with the instructions provided:

Steps for random image generator

  • Declare an array using JavaScript to store the images.
  • Provide the link or URL of images in the declared array. You can also pass the height and width in the array for the image size to display on the webpage.
  • Declare a JavaScript variable to store a random value calculated using this floor(Math.random*randomImage.length) method. It will generate a random number between 0 and the length of the array that will be assigned to the images to display randomly.
  • Now, return the random images selected using a number calculated in the previous step.
  • Put all the above steps in a user-defined function (getRandomImage), which will call by clicking on a Generate Image
  • In HTML code, we will use a tab and provide an ID to display an image over another image. So, the images will show you one by one, by overwrapping each other.

Convert these steps into actual implementation.

Copy Code

Example

<html>

<head> 

<title> Random Image Generator </title>

</head>

<script>

function getRandomImage() {

//declare an array to store the images

var randomImage = new Array();



//insert the URL of images in array

randomImage[0] = "https://images.pexels.com/photos/858115/pexels-photo-858115.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";

randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg";

randomImage[2] = "https://images.pexels.com/photos/142497/pexels-photo-142497.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";

randomImage[3] = "https://images.unsplash.com/photo-1543877087-ebf71fde2be1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60";

randomImage[4] = "https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg";

randomImage[5] = "https://images.unsplash.com/photo-1501265976582-c1e1b0bbaf63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60";



//generate a number and provide to the image to generate randomly

var number = Math.floor(Math.random()*randomImage.length);



//return the images generated by a random number

return document.getElementById("result").innerHTML = '<img src="'+randomImage[number]+'" />';

}



</script>

<body>

<center><h2 style="color:green"> Random Image Generator </h2></center>

<h4> Click the button to generate and display random images on the webpage </h4>

<!-- call user-defined getRandomImage function after 2 seconds -->  

<button onclick = "setInterval(getRandomImage, 2000)"> Generate Image </button>

<br> <br>

<span id="result" align="center"> </span> 

  

</body>  

</html>

Output

Upon running this code, a webpage will be displayed featuring a button labeled "Generate Image". Upon clicking this button, images will be randomly showcased on the webpage.

Press the "Generate Image" button to view a randomly generated image. The images will refresh automatically every few seconds after clicking the "Generate Image" button.

See the output below:

Please bear in mind that we are using an array to store image addresses sourced from the internet. It's important to note that these images have not been saved or downloaded into our database.

Example 2: Generate multiple random images

In the following instance, we are going to produce and exhibit numerous random images simultaneously upon the user's selection of a button. The button will be crafted through HTML coding labeled as Generate Image. These images will be contained within an array that can be chosen by the user. Whenever the user triggers the Generate Image button, a set of five random images will be produced and showcased on the website.

See the steps below, how this will be done:

  • Declare an array using JavaScript and provide the link or URL of images in that array to store the images.
  • Use a for loop to generate multiple random images at once. We will use for loop of 0 to 5 to display five images in a single button click.
  • Put the below steps in this for loop.
  • Calculate a random number between 0 to length of the array using the floor(Math.random*randomImage.length) method. This generated number will assign to the images to display randomly.
  • Now, print all five random images selected using a number calculated in the previous step.
  • Put all the above steps in a user-defined function (getRandomImage), which will call by clicking on a Generate Image

Translate these instructions into executable code and refer to the code provided below:

Copy Code

Example

<html>

<head> 

<title> Random Image Generator </title>

</head>

<script>

function getRandomImage() {

//declare an array to store the images

var randomImage = new Array();



//insert the URL of images in array

randomImage[0] = "https://wi.wallpapertip.com/wsimgs/15-155208_desktop-puppy-wallpaper-hd.jpg";

randomImage[1] = "http://www.petsworld.in/blog/wp-content/uploads/2014/09/running-cute-puppies.jpg";

randomImage[2] = "https://wi.wallpapertip.com/wsimgs/156-1564365_golden-retriever-puppy-desktop-wallpaper-desktop-wallpaper-puppy.jpg";

randomImage[3] = "https://wi.wallpapertip.com/wsimgs/156-1564140_free-puppy-wallpapers-for-computer-wallpaper-cave-cute.jpg";

randomImage[4] = "https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg";

randomImage[5] = "https://wi.wallpapertip.com/wsimgs/156-1566650_cute-puppies-desktop-wallpaper-cute-puppies.jpg";



//loop to display five randomly chosen images at once

for (let i=0; i< 5; i++) {

//generate a number and provide to the image to generate randomly

var number = Math.floor(Math.random()*randomImage.length);

//print the images generated by a random number

document.getElementById("result").innerHTML += '<img src="'+ randomImage[number] +'" style="width:150px" />';

}

}



</script>

<body>

<center><h2 style="color:green"> Random Image Generator </h2></center>

<h4> Click the button to generate and display the five random images: </h4>

<!-- call user-defined getRandomImage function to generate image -->  

<button onclick = "getRandomImage()"> Generate Image </button>

<br> <br>

<span id="result" align="center"> </span> 

  

</body>  

</html>

Output

Executing the provided code will result in receiving a response along with a button labeled "Generate Image". It is important to note that initially, there will be no image displayed.

Upon clicking the 'Generate Image' button, a set of five randomly chosen images will be presented to you on the website.

Once more, select the Generate Image button to view an additional five images randomly, featuring the same output as before.

Approach 2

In this method, random images will be shown each time a button is clicked. Unlike the previous method, these images will not switch automatically.

In this instance, we will include the dimensions (both height and width) for each image to be shown on the webpage. Consequently, the images will appear in the dimensions specified within the JavaScript code.

Steps for random image generator

  • Create a user-defined function randomImageGenerator and put all the below steps inside it.
  • Create an array of images using JavaScript containing the location/URL, height, and width of the image to be displayed on the webpage.
  • Store the URL, height, and width of the images in another array index.
  • Generate a random number using floor method that will use the array of images to display on the webpage randomly. It will generate a random number between 0 to the length of the array that will be assigned to the images to display randomly.
  • Display the image whose index number matches with the random number generated in previous step.
  • We will use a method to remove the previous image and override with the new image.
  • Create a button in HTML to change the images.

Translate these instructions into practical application and examine the code provided underneath:

Copy Code

Example

<html>

<head>

<title>Display random images</title>

<style>

body {

margin-top: 30px;

}

</style> 

</head>



<script>

function displayRandomImages() 

{

   //array of images with image location, height, and width

   var imageArray = [

   { 

     //address URL of the image

     src: "https://wi.wallpapertip.com/wsimgs/15-155208_desktop-puppy-wallpaper-hd.jpg",

     //size for the image to be display on webpage

     width: "280",

     height: "200"

   }, 

   {

     src: "https://wi.wallpapertip.com/wsimgs/156-1564365_golden-retriever-puppy-desktop-wallpaper-desktop-wallpaper-puppy.jpg",

     width: "320",

     height: "195"

   }, 

   {

     src: "https://wi.wallpapertip.com/wsimgs/156-1564140_free-puppy-wallpapers-for-computer-wallpaper-cave-cute.jpg",

     width: "320",

     height: "195"

   },

   {

     src: "https://wi.wallpapertip.com/wsimgs/156-1566650_cute-puppies-desktop-wallpaper-cute-puppies.jpg",

     width: "350",

     height: "250"

    } ];

    

    //find the length of the array of images

    var arrayLength = imageArray.length;

    var newArray = [];

    for (var i = 0; i < arrayLength; i++) {

        newArray[i] = new Image();

        newArray[i].src = imageArray[i].src;

        newArray[i].width = imageArray[i].width;

        newArray[i].height = imageArray[i].height;

    }

   

  // create random image number

  function getRandomNum(min, max) 

  {

      // generate and return a random number for the image to be displayed 

      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;

      return newArray[imgNo];

  }  



  // 0 is first image and (preBuffer.length - 1) is last image of the array

  var newImage = getRandomNum(0, newArray.length - 1);

 

  // remove the previous images

  var images = document.getElementsByTagName('img');

  var l = images.length;

  for (var p = 0; p < l; p++) {

     images[0].parentNode.removeChild(images[0]);

  }

  // display the new random image  

  document.body.appendChild(newImage);

}

</script>



<body>

<div>

<center>

<h2 style="color:green"> Random Image Generator </h2>

<h4> Press the button to display and change the image </h4>

<button onclick="displayRandomImages();"> Display Images </button>

</center> 

</div>

</body>

</html>

Output

Upon running the provided code, a webpage will be displayed featuring a button labeled "Display Image". Upon clicking this button, an image will be generated.

An image is shown at random every time the Display Images button is clicked.

Each time you select the Display Images button, a fresh image will be displayed.

Let's break down the JavaScript code provided above into simple steps to facilitate better comprehension.

Declare and initialize an array

Create an array to hold the details of the image that will be shown on a website, including the location, height, and width.

Example

var imageArray = [

   { 

     //address URL of the image

     src: "https://wi.wallpapertip.com/wsimgs/15-155208_desktop-puppy-wallpaper-hd.jpg",

     //size for the image to be display on webpage

     width: "280",

     height: "200"

   }, 

   {

     src: "https://wi.wallpapertip.com/wsimgs/156-1564365_golden-retriever-puppy-desktop-wallpaper-desktop-wallpaper-puppy.jpg",

     width: "320",

     height: "195"

   }];

Save the URL, height, and width of the image into a different index within an array.

This script is designed to transfer the URL, height, and width of an image to a different array index for convenient access. To achieve this, the code calculates the size of the original array and then copies each element to a new array.

Example

//find the length of the array of images

    var arrayLength = imageArray.length;

    var newArray = [];

    for (var i = 0; i < arrayLength; i++) 

   {

        newArray[i] = new Image();

        newArray[i].src = imageArray[i].src;

        newArray[i].width = imageArray[i].width;

        newArray[i].height = imageArray[i].height;

    }

Generate a Random Number

This function will produce a random number within the range from 0 to the size of the array.

Example

function getRandomNum(min, max) 

  {

      // generate and return a random number for the image to be displayed 

      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;

      return newArray[imgNo];

  }  



  // 0 is first image and (preBuffer.length - 1) is last image of the array

  var newImage = getRandomNum(0, newArray.length - 1);

Remove the previous image

This script is designed to eliminate the existing image on the website, allowing the new image to be shown instead.

Example

// remove the previous images

  var images = document.getElementsByTagName('img');

  var l = images.length;

  for (var p = 0; p < l; p++) {

     images[0].parentNode.removeChild(images[0]);

  }

Display the image

We have successfully implemented this code to showcase the new image following the removal of the previous one.

Example

// display the new random image  

  document.body.appendChild(newImage);

Input Required

This code uses input(). Please provide values below: