Chizbe Joe
Chizbe Joe

Reputation: 35

Randomly Changing Images from an Array of Images

The title basically says it all.

I am trying to change an image to a random image from an array of images (hope that makes sense lol).

How can I create an array of images and then have the image change to a random image when something is clicked?

<h1>These are just placeholders</h1>
<p>I just want these images to randomly change to an image from an array of images each time they are shown (when "display" isn't "none")</p>
<img src="https://pixabay.com/static/uploads/photo/2013/11/21/07/30/icon-214446_960_720.jpg" class="newsAD"></img>
<img src="https://pixabay.com/static/uploads/photo/2013/11/21/07/30/according-to-214445_960_720.jpg" class="newsAD"></img>

<style>
    .newsAD {
      width: 150px;
      height: 150px;
      margin-left: 50px;
      background: skyblue;
      cursor: default;
      box-shadow: 1px 2px 5px 1px rgba(0, 0, 0, 0.4);
    }
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
function changeImageToRandomImage() {
 // something here that changes image to random image from array of images
}
</script>

Here's a fiddle.

Upvotes: 0

Views: 2346

Answers (2)

John the User
John the User

Reputation: 640

In such a situation you would store images somewhere and then store their paths in the array and call them like such:

HTML

<img onclick="changeImageToRandomImage()" id="image" src="img/image_0.jpg">

JavaScript

function changeImageToRandomImage() {
   images = ['img/image_1.jpg', 'img/image_2.jpg','img/image_3.jpg','img/image_4.jpg'];

   var random = images[Math.floor(Math.random()*images.length)];
   document.getElementById('image').src= random;

}

Upvotes: 3

Doron at Cloudinary
Doron at Cloudinary

Reputation: 34

This example shows how to do that with a regular (non-Ajax) web page where the images are listed in an array and the random number generated is used to selected a specific image from it. Another approach is to implement the random image selection on the server side (e.g. NodeJS) and use the same Ajax call on the client to trigger the server selector logic.

Upvotes: 0

Related Questions