How To Select Random Image in An Array Using JavaScript

How To Select Random Image in An Array Using JavaScript

Selecting a random image from an array in JavaScript can add an element of fun and dynamism to your web projects. This process involves storing image URLs in an array and using JavaScript to randomly select one of these URLs to display on the webpage. By following a few simple steps, you can create a random image generator that will enhance the user experience of your website. In this tutorial, we will guide you through the process of selecting a random image from an array using JavaScript, providing you with the code and explanations needed to implement this feature in your own projects.

Let’s Get Started –

<html>
<head>
<title>Random Image Genrator</title>
</head>
<script>
function getRandomImage() {
//declare an array to store images
var randomImage = new Array();
//0,1,2,3,4,5
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.unsplash.com/photo-1543877087-ebf71fde2be1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60";
randomImage[3] = "https://images.pexels.com/photos/142497/pexels-photo-142497.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
randomImage[4] = "https://images.unsplash.com/photo-1501265976582-c1e1b0bbaf63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60";
randomImage[5] = "https://wi.wallpapertip.com/wsimgs/156-1565522_puppies-desktop-wallpaper-desktop-background-puppies.jpg";

// genrate a number and provide to genrate image accordingly
var number = Math.floor(Math.random()*randomImage.length);
// return the images which are genrated
return document.getElementById('result').innerHTML = '<img src="' + randomImage[number]+'" />';
}
</script>
<body>
<center><h2 style="color:red;"> Random Image Generator</center></h2>
<h4> Click the button to genrate random images</h4>
<button onclick="setInterval(getRandomImage, 2000)"> Generate Image</button>
<br> <br>
<span id="result" align="center"> </span>
</body>
</html>

Explanation:

  1. HTML Structure:
    • <html>: The root element of an HTML page.
    • <head>: Contains meta-information about the document, such as its title.
    • <title>: Sets the title of the document as displayed in the browser tab.
    • <script>: Allows embedding JavaScript code in the document.
    • <body>: Contains the content of the document that is displayed in the browser window.
    • <center>: Deprecated tag that centers the content within it. Not recommended for use; CSS should be used for styling instead.
    • <h2>: Heading level 2 element for the title of the page.
    • <h4>: Heading level 4 element for a subheading.
    • <button>: Creates a clickable button element.
    • <br>: Line break element to add vertical space.
    • <span>: Inline container used to group and style text or inline elements.
  2. JavaScript Function (getRandomImage):
    • function getRandomImage() { ... }: Defines a function named getRandomImage that generates a random image and displays it on the page.
    • var randomImage = new Array();: Declares an array named randomImage to store image URLs.
    • randomImage[0] = "...";: Assigns URLs to elements in the randomImage array.
    • Math.floor(Math.random()*randomImage.length);: Generates a random number between 0 and the length of the randomImage array (exclusive).
    • document.getElementById('result').innerHTML = '...';: Sets the inner HTML of the element with the ID result to an image tag with a randomly selected URL from the randomImage array.
  3. Event Handling:
    • onclick="setInterval(getRandomImage, 2000)": Sets an event listener on the button so that when it is clicked, the getRandomImage function is called every 2000 milliseconds (2 seconds).
  4. Output:
    • When the page is loaded, it displays a title (Random Image Generator), a subheading, a button labeled Generate Image, and an empty space (<span id="result"></span>) where the random image will be displayed.

Output

If You wish you can watch the video tutorial also

Conclusion-

In conclusion, selecting a random image from an array using JavaScript is a straightforward process that can significantly enhance the visual appeal of your website. By following the steps outlined in this tutorial, you can create a dynamic and engaging user experience that will captivate your audience. Whether you are building a portfolio, a blog, or an e-commerce site, implementing a random image generator can add a touch of creativity and excitement. We hope this tutorial has been helpful, and we look forward to seeing the innovative ways you incorporate random image selection into your web projects.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>