Assigning background color to classes from array

I have six div's on a page that each have the same class. I am trying to assign each of them one unique color that I have chosen in an array. I don't want any of them to have the same color.

I've successfully assigned each of the divs a background color from an array, however, some of the classes can get the same background color since its currently just choosing the color randomly from the array.

jQuery(document).ready(function($) {
$(".et_pb_post").each(function() {
  var colors = ["#CFEAEA ","#c9e3d5","#e7dadd","#dde9eb","#ecfac7","#facba9","#dfdbd3","#f1fdc1"];                
  var rand = Math.floor(Math.random()*colors.length);    
    $(this).css("background-color", colors[rand]);
});
});

and then the html is something like

<div class="et_pb_post">Some content with bg-color A</div>
<div class="et_pb_post">Some content with bg-color B</div>
<div class="et_pb_post">Some content with bg-color C</div>
<div class="et_pb_post">Some content with bg-color D</div>

How do I make sure all of the background-colors are unique?

Thanks a lot!

5 answers

  • answered 2019-07-18 14:52 neuhaus

    I suggest you first shuffle the array with the random values as described at

    How to randomize (shuffle) a JavaScript array?

    Then whenever you use a value from the array, you remove it from the array using pop() (or shift()).

    That way you make sure every value from the array is only used once.

  • answered 2019-07-18 14:52 Taki

    On way you can do this is to create a copy of the colors array and remove the color from it whenever it's picked for a div :

    jQuery(document).ready(function($) {
      var colors = ["#CFEAEA ", "#c9e3d5", "#e7dadd", "#dde9eb", "#ecfac7", "#facba9", "#dfdbd3", "#f1fdc1"];
    
      var copy = [...colors];
    
      $(".et_pb_post").each(function() {
    
        var rand = Math.floor(Math.random() * copy.length);
        $(this).css("background-color", copy[rand]);
    
        copy = copy.filter(color => color !== copy[rand]);
    
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="et_pb_post">Some content with bg-color A</div>
    <div class="et_pb_post">Some content with bg-color B</div>
    <div class="et_pb_post">Some content with bg-color C</div>
    <div class="et_pb_post">Some content with bg-color D</div>

  • answered 2019-07-18 14:52 jogi

    You can get a group of elements from the dom, one for each div like this:

    var divElements = document.getElementsByClassName("et_pb_post");
    

    then you can loop thru and use the same loop counter as index in your bg color array to assign the property to each div element...

    for (var i = 1; i < colors.length; i++)
    {
        divElement[i].style.backgroundColor = colors[i];
    }
    

    the key is using a single loop and index to coordinate between the two arrays, divs and colors.

  • answered 2019-07-18 14:53 LuudJacobs

    You could remove the chosen color from the array of colors, so it can't be picked again. As a bonus I've removed jQuery for you.

    // define colors
    let colors = ["#CFEAEA", "#c9e3d5", "#e7dadd", "#dde9eb", "#ecfac7", "#facba9", "#dfdbd3", "#f1fdc1"];
    
    // get all .et_pb_post elements and loop over 'em
    document.querySelectorAll('.et_pb_post')
      .forEach((post) => {
        // get random color
        const randomColor = colors[Math.floor(Math.random() * colors.length)];
    
        // set background color for current post
        post.style.backgroundColor = randomColor;
    
        // filter colors to remove randomColor from the array
        colors = colors.filter((color) => color !== randomColor);
      });
    

  • answered 2019-07-18 15:11 loki97

    jQuery(document).ready(function($) {
    var index = 0;
    $(".et_pb_post").each(function(item) {
      var colors = ["#CFEAEA ","#c9e3d5","#e7dadd","#dde9eb","#ecfac7","#facba9","#dfdbd3","#f1fdc1"];
      var colorsLength = colors.length;
      var colorIndex = index%colorsLength;   
        $(this).css("background-color", colors[colorIndex]);
        index++;
    });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="et_pb_post">Some content with bg-color A</div>
    <div class="et_pb_post">Some content with bg-color B</div>
    <div class="et_pb_post">Some content with bg-color C</div>
    <div class="et_pb_post">Some content with bg-color D</div>