tags:

views:

67

answers:

4

Hi Guys,

I am fairly new to jQuery and I am trying to rotate 6 CSS classes

.img
.img1
.img2
.img3
.img4
.img5

Only one of these classes has "display:block;" the rest have "display: none;".

I am trying to basically randomize the appearance of these classes - for these 6 classes - by making the current "display: block" goto "display: none" and then another class change to "Display:block" each time the page loads ?

Would anyone be able to help ?

+1  A: 
var ran = rand(0,5)
$('.img').hide();
$('.img' + ran).show();

Give all the elements 2 classes 1 'img' and then a unique class 'img1,img2 etc'

Pino
Right, multiple classes, well done +1
Yar
I just read that last line, but shouldnt the unique class start with 'img0'
TStamper
Yea, if you want to make it start with 1 just add +1 to the ran var
Pino
A: 

Just modify the class of all pictures exclude the one which was randomly choosen.

pseudo code:

var img_id = rand(0,5);

for (i=0;i<5; ++i)
{
   if (i!=img_id)
      $("image_"+img_id).class = hiddenclass;
}
Aif
A: 

Your question is unclear.

I assume that you're trying to randomly show all elements that match one of those classes.

You can generate a random number between 0 and 6 by writing parseInt(Math.random() * 6, 10).

You can therefore write something like this: (and change .img to .img0)

var indexToShow = parseInt(Math.random() * 6, 10);

for(var i = 0; i <= 6; i++) {
    if(i === indexToShow)
        $('.img' + i).show();
    else
        $('.img' + i).hide();
}

If you make another class (eg, .img) and add it to all of the elements, you could make it simpler:

$('.img').hide();
$('.img' + parseInt(Math.random() * 6, 10)).show()
SLaks
A: 

Choose one to show, then hide them all, filter by the class you want to show, and display it. It will be easier if you give them all a common class, say img to make the global selection easier.

var showClass = '.img' + parseInt(Math.random() * 6, 10);

$('.img').hide().filter(showClass).show();
tvanfosson