Randomly Add a Class in For Loop

jquery

Solution

Simply use Math.random().

In pseudo-code:

if (Math.random() < .5) //Or any other fraction
   addDivWithPossibleClass();
else
   addDivWithoutPossibleClass();

Problem

On document ready, I am populating variables and using them to run a for-loop that creates a number of divs with a class of `box`. I would like to add a class of `possible` to those `box` divs at random so that they are evenly distributed. For example, say there ends up being 100 divs with class `box`, I'd like a random number of those divs to also have a class of `possible`. Any ideas as to how I can do this? I have included my current code below. Thanks ``` $(document).ready(function() { var wrapper = $('.wrapper'); var wrapperWidth = wrapper.width(); var wrapperHeight = wrapper.height(); var wrapperArea = wrapperWidth * wrapperHeight; var boxWidthHeight = 30; var boxArea = boxWidthHeight * boxWidthHeight; var boxCount = wrapperArea / boxArea; alert(boxCount); for(var i = 0; i < boxCount; i++) { $('.wrapper').append('<div class="box"></div>'); } }); ```

Original source