MRC
MRC

Reputation: 553

Set random <IMG> inside a div to have a class

I have a stack of images, which some JS code fades between the images.

The active image, has an "active" class.

How can I set a random image to have the class so that it never starts from the same place on page loading?

<div id="quote">
    <img class="active" src="http://dicktyler.com/dev/images/quote1.png" />
    <img src="http://dicktyler.com/dev/images/quote2.png" />
    <img src="http://dicktyler.com/dev/images/quote3.png" />
    <img src="http://dicktyler.com/dev/images/quote4.png" />
</div>

Upvotes: 0

Views: 162

Answers (3)

Nick R
Nick R

Reputation: 7784

You could do something like this:

var items = $('#quote img');
var random = Math.floor(Math.random() * items.length);
items.eq(random).addClass('active');

JSFiddle Demo

This will generate a number between 0 and the img length, which would be 4 in this case. Then we can use eq() to select the image with our randomly generated number.

Upvotes: 4

Adam Merrifield
Adam Merrifield

Reputation: 10407

The easiest way to do this is to get all the img's in a jQuery object. Next use eq to select a specific one from the list. For the value of the eq use Math.random() * $imgs.length this will give you a number between 0 & however many images there are exclusivly.

var $imgs = $('#quote img');

$imgs.eq(Math.floor(Math.random() * $imgs.length)).addClass('active');

Upvotes: 2

Smith Smithy
Smith Smithy

Reputation: 585

What i would do:

first count the images

total_images = $('#quote img').length;

then generate a random number between 0 and the total

random_num = Math.random() * (total_images - 0) + 0;

Then assign the active class to that by selecting it as a child of #quote

$('#quote img:nth-child(random_num)').addClass('active');

make it a function:

function set_random_img(div){
    total_images = $('#'+div+' img').length;
    random_num = Math.random() * (total_images - 0) + 0;
    $('#'+div+' img:nth-child(random_num)').addClass('active');
}

and call it:

set_random_img('your_div_id');

Upvotes: 1

Related Questions