twario
twario

Reputation: 49

Choose random image for every image Javascript

//Setting up the Array

var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];

// creating the randomizing

var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];


// image source looks for the attribute, by using the variable arraying
$('img').attr('src',random);

Above is my code. I currently have javascript set up this way. The current code has the piece where images are randomly replaced from an image from the array. I want to have the code state that switch every image with a new random image, not every image with the same time. I like how it is random every time, but I also want to random for each picture.

Upvotes: 0

Views: 249

Answers (2)

Guffa
Guffa

Reputation: 700472

You can use a callback function with the attr method to calculate the value for each element:

$('img').attr('src', function(){
  return arrayImg[Math.floor(Math.random()*arrayImg.length)];
});

Upvotes: 0

tymeJV
tymeJV

Reputation: 104785

Set up a loop to go over each image, pick a random one, and then assign to that one:

var arrayImg =['http://www.whattofix.com/images/PoliticalAnimal.jpg','http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg','http://cdn.trendhunterstatic.com/thumbs/suit-animal-art-berkley-illustrations.jpeg','http://img1.etsystatic.com/016/1/7647665/il_340x270.411173311_ojy5.jpg'];

$("img").each(function() {
    var random = arrayImg[Math.floor(Math.random()*arrayImg.length)];
    $(this).attr('src',random);
});

Upvotes: 1

Related Questions