0
//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.

2
  • What do you mean? You end up having the same picture sometimes? Commented Nov 20, 2013 at 14:32
  • you mean you dont wanna repeat image ? Commented Nov 20, 2013 at 14:32

2 Answers 2

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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)];
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.