Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a random class to every element specified

Tags:

jquery

css

random

I am trying to add a random class to even < li > element within my #container div

Here is my code:

$( "#container li" ).each(  

  $().ready(function() {

        $("#container li:random").addClass("one");
        $("#container li:random").addClass("two");
        $("#container li:random").addClass("three");

    })
    );

The problem is that I have ten < li > elements and I want each of these elements to receive one of the three possible classes in a random fashion.

However my code above only assignes three < li > elements with the classes leaving the remaining seven < li > elements class-less.

I have tried other snippets of code but none of which randomly apply a list of classes to ALL elements specified.

I have tried snippets from this post HERE but none of which produce the desired result of making sure all elements get a random class.

Thank you for your help.

like image 470
Wordpressing Avatar asked Oct 07 '11 11:10

Wordpressing


People also ask

How do you loop through all elements in the same class?

Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.

How does random class work in c#?

The current implementation of the Random class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times.


1 Answers

You can use an array of classes and then assign a random class from that array to each element matching a selector like this:

$(document).ready(function(){
    var classes = ["one", "two", "three"];

    $("#container li").each(function(){
        $(this).addClass(classes[~~(Math.random()*classes.length)]);
    });
});

If you want to ensure that each class is only used once, you can remove it from the array when it is used:

$(document).ready(function(){
    var classes = ["one", "two", "three"];

    $("#container li").each(function(){
        $(this).addClass( classes.splice( ~~(Math.random()*classes.length), 1 )[0] );
    });
});
like image 192
Paul Avatar answered Nov 15 '22 04:11

Paul