javascript - Generating divs each with random class from the array -


i'm having trouble figuring out why following function not achieving should:

function example() {     var $element;     var rndclass;     var classesarr = ['one', 'two', 'three'];     var container = $('.container');      for(i=0; i<10; i++) {         rndclass = math.floor(math.random()*classesarr.length);         $element = $('</div>', {'class': 'card '+classesarr[rndclass]+''});         $(container).append($element);     }  } 

in nutshel want generate 10 divs each having class of card + class classesarr (array) selected randomly , after append each of these divs container div, far nothing seems happening. here jsfiddle https://jsfiddle.net/u5llx8gq/4/

as sidenote, great if guys suggest better way these random clases, there should more or less equal amount of these used in 10 divs.

to more or less number of class types while still selecting @ random can this.

jquery(function($) {    var classes = ['card-1', 'card-2', 'card-3'],        classes_cpy = classes.slice(),        = 10,        ran;      (; i--;) {      ran = (math.random() * classes_cpy.length) | 0;      $('body').append(        $('<div>', {          'text': i,          // remove , return random string array          'class': 'card ' + classes_cpy.splice(ran, 1)[0]        })      );      // reload array values when empty      if (classes_cpy.length === 0) {        classes_cpy = classes.slice();      }    }  });
.card-1 { background-color:green; }  .card-2 { background-color:red; }  .card-3 { background-color:pink; }  .card { border:1px solid white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -