0

I have two divs and I want to add the class ".active" to only one of them at random.

This is the best I could come up with, however, sometimes both divs get the class added.

randomClass: function(){
        var classes = ["active", ""];
         $(".contain > div").each(function(){
           $(this).addClass(classes[~~(Math.random()*classes.length)]);
        });
    },

HTML

 <div class="contain">
    <div></div>
    <div></div>
 </div>
Spencer Pope
  • 455
  • 6
  • 23
  • 2
    For those that don't know that the double tilde does: http://stackoverflow.com/questions/4055633/what-does-double-tilde-do-in-javascript – j08691 Mar 13 '17 at 19:03
  • you can get an array of div inside .contain div and use math random for random index in that array to add class active to div – Filip Kováč Mar 13 '17 at 19:07

3 Answers3

1

I wrote the following code to use the eq. It will select a random number between the valid indexes and then return that value and then append the proper class. I added one line to remove whichever one currently has the class active, so the button would work.

Important logic error with your code: by using .each you are not guaranteeing that both or none are not selected. You have to select the object before hand.

With your code, here is the possible out comes (where 1 is active and 0 is not active):

1 0
0 1
1 1
0 0

There is a 50% chance your code will not work as intended.

So, I wrote mine a little differently.

function randomClass(){
 $(".contain > div").removeClass("active");
 $(".contain > div").eq(Math.floor(Math.random()*$(".contain > div").length)).addClass("active");
}


randomClass();
.active {
 background-color:red;
}
.box {
 width:50px;
 height:50px;
 border:1px solid black;
 margin:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contain">
 <div class="box"></div>
 <div class="box"></div>
</div>

<button onclick="randomClass()">New Random</button>
Neil
  • 14,063
  • 3
  • 30
  • 51
0

The eisiest way based on your code:

randomClass: function(){
        var classes = ["active", ""];
         $(".contain > div").each(function(){
            var random = Math.random();
            var classesLength = classes.length;
            var index = ~~(random*classesLength);
            index = index <= classesLength - 1 ? index : index -1;
            $(this).addClass(classes.splice(index, 1)[0]);
        });
    },

You can add different numbers of your class list and classes will never repeat if it will be unique in array classes

Pavlo Zhukov
  • 3,007
  • 3
  • 26
  • 43
0

Here is one simple solution to your problem:

// from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive
function getRandomIntInclusive(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomClass() {
  var className = 'active';
  var elements = $('.contain > div');
  elements.removeClass(className);
  var index = getRandomIntInclusive(0, elements.length - 1);
  elements.eq(index).addClass(className);
}

randomClass();
.contain div {
  border: 1px solid;
  width: 20px;
  height: 20px;
  margin: 10px;
}

.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contain">
    <div></div>
    <div></div>
 </div>
Adam Chwedyk
  • 418
  • 4
  • 8