Reputation: 1573
Bit of an odd request. I have ~300 image URLs and 27 div
s. Each div
has an id="img1"
, where 1
is a number between 1 and (you guessed it) 27, and a class="imageblock"
(for general styling).
Into each of these div
s, I'd like to insert an <img src="http://foo.bar/img.jpg" width="640">
, where the URL is chosen from a list of about 300 randomly, and inserted into one of the div
s randomly. Each of the 27 div
s should have its own image chosen from the 300 options.
Furthermore, these images should cycle. Every 5 seconds, I'd like to have one random image URL on the page replaced with another random one.
This is the (terrible) code I have attempted to cobble together with a little help, but I'm useless with javascript and can't make this work:
<script type="text/javascript">
$('document').ready(function() {
var divs = $('div');
$("div").each(function() {
$(this).html("<img src='http://foo.bar/img1.jpg'alt='"+$(this).attr("id")+"'/>");
});
var imageChanger = setInterval(function() {switchImage()}, 500);
function switchImage() {
var new_image_url = [ 'http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];
var random_div = Math.floor(Math.random() * $('div').length);
var random_img = Math.floor(Math.random() * $(new_image_url.length);
$("div:nth-child("+random_div+")").html('<img src="('+random_img+')" width="640">)');
}
});
</script>
Note that the remote images do not follow any common pattern, thereby rendering my random_img
variable unworking.
Any help would be appreciated.
Upvotes: 1
Views: 711
Reputation: 298166
To select a random element from an array, you can use this:
var random_div = divs[Math.floor(Math.random() * divs.length)];
var random_img = new_image_url[Math.floor(Math.random() * new_image_url.length)];
Here's a slightly more efficient version of your code:
function random_int(max) {
return Math.floor(Math.random() * max);
}
$(document).ready(function() {
var images = ['http://foo.bar/anotherimg.jpg', 'http://bar.foo/image.jpg', 'http://foo.bar/imgremote.jpg'];
var $divs = $('div');
$divs.each(function() {
$('<img />', {
src: 'http://foo.bar/img1.jpg',
alt: this.id
}).appendTo(this);
});
function switchImage() {
var $div = $divs.eq(random_int($divs.length));
var image = images[random_int(images.length)];
$div.find('img').attr('src', image);
}
var imageChanger = setInterval(switchImage, 500);
});
Upvotes: 5