LeTung LeTung - 1 month ago 9
CSS Question

Jquery: random background color

I have the following background colors:

#05668D, #028090, #00A896, #02C39A, #F0F3BD ...

When the page loads, how do I make each element with class
abc
have a different background color (may repeat, random), in one of the top colors.

Ex:

<div class="asd"><div class="abc">...</div></div>
<div class="asd"><div class="abc">...</div></div>
<div class="asd"><div class="abc">...</div></div>
<div class="asd"><div class="abc">...</div></div>
<div class="asd"><div class="abc">...</div></div>


Result:

<div class="asd"><div class="abc" style="background-color:#05668D">...</div></div>
<div class="asd"><div class="abc" style="background-color:#00A896">...</div></div>
<div class="asd"><div class="abc" style="background-color:#028090">...</div></div>
<div class="asd"><div class="abc" style="background-color:#00A896">...</div></div>
<div class="asd"><div class="abc" style="background-color:#F0F3BD">...</div></div>
...

Answer

You can use a random function like the one below and jquery's each function to apply a color to the elements.

		$(function(){
  
  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  };
  var colors = ['#05668D', '#028090', '#00A896', '#02C39A', '#F0F3BD'];
  $('.abc').each(function(index,el){
    var randomColorIndex = getRandomInt(0,colors.length-1);
    $(el).css('background-color',colors[randomColorIndex]);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="asd"><div class="abc">...</div></div>
    <div class="asd"><div class="abc">...</div></div>
    <div class="asd"><div class="abc">...</div></div>
    <div class="asd"><div class="abc">...</div></div>
    <div class="asd"><div class="abc">...</div></div>

You can read about both here:

jquery each function:https://api.jquery.com/each/

Javascript Random function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

Comments