0

How can I display a random image from a file of images with JQuery, then when a link is click the image is changed to another random image.

This is the img id where the image needs to be on the load and if a link above it is picked.

    <a href="#imageChange">

    <img id="cap" src="" height="220px" width="530px" />
mpiazza031
  • 67
  • 1
  • 10
  • `http://stackoverflow.com/questions/17142339/selecting-a-random-image-to-display?rq=1` Mr. Code did a very nice job in his answer and I think that will get you 95% of where you want to go. – zipzit Sep 23 '14 at 00:21
  • generate a [random number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) and create an array of the images then use that number in the array to select which image to load ....then generate a new number on click. – Matt Sep 23 '14 at 00:22

2 Answers2

0

If you keep the image paths in a database you could do:

SELECT imagePaths FROM table ORDER BY RAND() LIMIT 1

to fetch a random image path and then display it.

Using a client/server side language, you could generate a random number which will be the index you will use to get the image path from the array that store all your images.

In javascript you could use a function like that:

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

With PHP:

$index = rand(0, $nbOfImgs);
Adam Sinclair
  • 1,654
  • 12
  • 15
0

The jQuery snippet here would work once you get the image URL. theImageURL refers to the complete URL of the image.

$('#imageChange').on('click',function(event){
    event.preventDefault(); // to prevent page from jumping or navigating away
    $('#cap').attr('src',theImageURL); //setting the source for the image.
});

Alternately you can also invoke as $('#cap').load(theImageURL);

Vijaiendran
  • 71
  • 1
  • 6