How to iterate through classes in jQuery? -


the problem cards same color, each card given 1 of 5 colors @ random when page loads.

here code trying use:

$( document ).ready(function() {     onetofive = math.floor((math.random() * 5) + 1);     switch (onetofive) {         case 1:             randcolor = "rgba(255, 255, 255, 0.25)";             break;         case 2:             randcolor = "rgba(0, 0, 255, 0.25)";             break;         case 3:             randcolor = "rgba(0, 0, 0, 0.25)";             break;         case 4:             randcolor = "rgba(255, 0, 0, 0.25)";             break;         case 5:             randcolor = "rgba(0, 255, 0, 0.25)";             break;         default:             randcolor = "rgba(122, 122, 122, 0.25)";             break;     }      $(".card-color").each(function(){         $(".card-color").css("background-color", randcolor);     }); }); 

the main issue logic generate randcolor once when pages loads. make work require need generate random colour inside each() handler. need use this keyword reference current element within handler.

you can make code more succinct using array instead of switch. try this:

var colours = ['rgba(255, 255, 255, 0.25)', 'rgba(0, 0, 255, 0.25)', 'rgba(0, 0, 0, 0.25)', 'rgba(255, 0, 0, 0.25)', 'rgba(0, 255, 0, 0.25)', 'rgba(122, 122, 122, 0.25)'];    $(".card-color").each(function() {    var rnd = math.floor(math.random() * 5);    $(this).css("background-color", colours[rnd]);  });
.card-color {    width: 20px;    height: 20px;    margin: 5px;    display: inline-block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>  <div class="card-color"></div>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -