Chizbe Joe Chizbe Joe - 3 years ago 100
jQuery Question

(SOLVED) 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="" class="newsAD"></img>
<img src="" class="newsAD"></img>

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

<script src="">
function changeImageToRandomImage() {
// something here that changes image to random image from array of images

Here's a fiddle.

EDIT: This has been solved - Working example

Answer Source

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


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


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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download