Randomly adding a class to a loop

In the finished document, I populate the variables and use them to start the for loop, which creates several divs with the box class. I would like to add the possible class to those box divs randomly so that they are evenly distributed. For example, let's say that we end up with 100 divs with the box class, I would like a random number of these divs to also have the possible class.

Any ideas on 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>'); } }); 
+4
source share
4 answers

Just use Math.random ().

In pseudo code:

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

Do you mean:

 for(var i = 0; i < boxCount; i++) { var newClass = "box" + ((i % 2 == 0) ? " posible" : ""); $('.wrapper').append('<div class="'+newClass+'"></div>'); } 
+1
source

Im no pro but i got it by doing this

 $(document).ready(function() { var wrapper = $('.wrapper'); var wrapperWidth = wrapper.width(); var wrapperHeight = wrapper.height(); var wrapperArea = wrapperWidth * wrapperHeight; var boxWidthHeight = 31; var boxArea = boxWidthHeight * boxWidthHeight; var boxCount = 30; //alert(boxCount); for(var i = 0; i < boxCount; i++) { $('.wrapper').append('<div class="box'+getRandom()+'">'+i+'</div>'); } function getRandom() { //get a random number between 1 and 10 var randomSomething = Math.floor((Math.random()*10)+1); // if the number is over 5 return the "possible" class else dont if(randomSomething > 5){ return ' possible'; }else{return '';} } }); 

increase or decrease the value of 10 to affect the number of random possibilities.

0
source

This will help a lot here.

 for(var i = 0; i < boxCount; i++) { // generating a random number between boxCount var randomnumber = Math.floor(Math.random()*boxCount) //checking if that is odd or even, based on that giving out result if (randomnumber%2 == 0) { $('.wrapper').append('<div class="box"></div>'); } else { $('.wrapper').append('<div class="box possible"></div>'); } } 
0
source

Source: https://habr.com/ru/post/1415893/


All Articles