I’m trying to switch randomly some images within 4 divs, but I’m having trouble with repeated results.
In spite of having per example
1, 4, 2, 3
and then
4, 1, 3, 2
I’m getting
2, 2, 4, 2 and then 1, 3, 3 ,4
So I need to find a solution to avoid repeating numbers
this is the code
var tempo = setInterval(function() {
$('.pub').each(function(i) {
var imagens_pubs = ['img_1.jpg', 'img_2.jpg', 'img_3.jpg', 'img_4.jpg'];
var rand = Math.floor(Math.random()*imagens_pubs.length);
$(this).html('<a href="http://www.mysite.com" target="_blank"><img src="pubs/'+imagens_pubs[rand]+'" width="220px" height="50px"></img></a>');
});
}, 5000);
This is because for each
.pub, you’re choosing a random item from the same array. The easiest way to do this would be to remove the element once you’ve chosen it, to stop repeated selections.Note we’ve moved the declaration of
imagens_pubout of theeach(), otherwise the array will be re-declared for each.pub.You can see this working here; http://jsfiddle.net/3xcKb/