1

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 ?

2
  • 1
    so you want it to switch between display:block and display:none which is only two options, so why 6 classes? Commented Oct 29, 2009 at 11:54
  • I'm not quites sure what you mean. Are these classes being applied to DOM elements and you want those DOM elements to have a random class assigned on each page load? Commented Oct 29, 2009 at 11:54

5 Answers 5

1
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'

Sign up to request clarification or add additional context in comments.

2 Comments

I just read that last line, but shouldnt the unique class start with 'img0'
Yea, if you want to make it start with 1 just add +1 to the ran var
0

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;
}

Comments

0

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()

Comments

0

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();

Comments

0

You can randomize your styles using JQuery. Look at this example on CodePen: http://codepen.io/aziev/pen/xwpREN

// put in this array your classes
classes = ['class1', 'class2', 'class3'];

max = classes.length - 1;
currentClass = Math.round(Math.random() * max);

// change '.block' to selector of your element
$('.block').addClass(classes[currentClass]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.