I am currently building a site whereby they would like each image on load to display different images. I have so far been able to target these and randomise them but it is applying the same image to all of the items. If you could see where I'm going wrong it would be great
var description = [
"http://placehold.it/300x300",
"http://placehold.it/200x200",
"http://placehold.it/100x100"
];
var size = description.length
var x = Math.floor(size*Math.random())
$('.item img').each(function() {
if($("img").hasClass("people")) {
$(this).attr("src",description[x]);
}
});
You should not define random number globally. May be below code will help you.
There seems to be 2 problems with your code:
Your randomizer is outside the
.each
loop. Hence why all your images get the same image.All images get the src attribute, even those without the
people
class.You nearly got it right though. Try a fiddle I made with these corrections, or the demo below.
Note that there are 4
items
here, but one is without thepeople
class and correctly isn't set to an image (only 3 are).You have some error in your code. you define
if($("img".
and that check the firstimg
but you want each imgx
does not change. You can usesetTimeout()
within$.each()
to push random element of array to an array without duplicates; utilize selector$(".item img.people")
set<img>
src
with.attr(function)
which iterates all elements in collection of original selector