Setting background colors for classes based on an array

I have a total of six div elements on a single page, all sharing the same class. My goal is to give each one a unique color from an array I have prepared. I want to avoid any repetition of colors among these divs.

Currently, I have managed to assign background colors to each div from the array randomly. However, there is a chance that some divs might end up with the same color due to the random selection process.

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]);
});
});

The corresponding HTML code looks something like this:

<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>

Is there a way to ensure that each background color used is truly unique?

Thank you for your assistance!

Answer №1

If you're looking to achieve this, one method is to duplicate the colors array and eliminate the selected color from it whenever it's assigned to 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>

Answer №2

To start, I recommend shuffling the array with random values by following the steps outlined here:

How to randomize (shuffle) a JavaScript array?

After shuffling, each time you use a value from the array, be sure to eliminate it using pop() (or shift()).

This method guarantees that every value in the array is used only once.

Answer №3

If you want to select a group of elements from the DOM, such as divs, you can do so like this:

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

From there, you can iterate through each element using a loop and assign background colors from an array based on the loop counter.

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

The key here is utilizing a single loop with an index to coordinate between the two arrays - one containing the div elements and the other holding the colors.

Answer №4

To ensure that a color is not repeated, you can eliminate the selected color from the list of available colors. Additionally, I have eliminated the need for jQuery in this code snippet.

// define an array of colors
let colors = ["#CFEAEA", "#c9e3d5", "#e7dadd", "#dde9eb", "#ecfac7", "#facba9", "#dfdbd3", "#f1fdc1"];

// iterate through all elements with the class .et_pb_post
document.querySelectorAll('.et_pb_post')
  .forEach((post) => {
    // select a random color from the colors array
    const randomColor = colors[Math.floor(Math.random() * colors.length)];

    // set the background color of the current post element
    post.style.backgroundColor = randomColor;

    // update the colors array to remove the selected randomColor
    colors = colors.filter((color) => color !== randomColor);
  });

Answer №5

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">Content with background color A</div>
<div class="et_pb_post">Content with background color B</div>
<div class="et_pb_post">Content with background color C</div>
<div class="et_pb_post">Content with background color D</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to display an updated value in a dialog window using an ajax response for the second time, the change

Upon submission of my form, a PHP script is triggered via AJAX to perform validation. Currently, the script simply echoes the post value. For example, if a user inputs "Dog" into "formEntry," the AJAX response will display Dog. However, if the user cancels ...

Managing dynamically appearing elements in Ember: Executing a Javascript function on them

I'm currently working on a project in Ember and facing an issue with calling a JavaScript function when new HTML tags are inserted into the DOM after clicking a button. Below is a snippet of my code: <script type="text/x-handlebars" id="doc"&g ...

Centering a Font Awesome icon within its parent element

Below is the code I am using: <div style="width:60px; height:60px; background-color: lightgrey;"> <a class="" href="javascript:void(0)" style="color: black; width: inherit; height: inherit;"> <i class="fa fa-lg fa-play" aria-hidden="t ...

Determining the percentage between two elements using Bootstrap 4's range slider

I've been searching everywhere but haven't found a solution. I am trying to implement Bootstrap 4.5's range slider to distribute the % difference between Client and Company, ranging from 1% to 100%. However, I am struggling with the jquery/j ...

When Components in Vue are called in a Single File, certain elements may not be displaying as expected

I have just finished creating my components using Vue 2, Vuetify, and Vue cli - 4.5.15. I attempted to combine them into a Single Vue file but encountered issues with the components not displaying <v-icons>, <v-textfield>, and some other elemen ...

Prevent sidebar from adjusting size according to text length

Just started exploring Bootstrap 5 and noticed some significant differences from version 4. Check out this jsfiddle for a demonstration of my issue. The problem occurs when the lorem ipsum text exceeds a certain length, causing the sidebar width to be pu ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

How can I locate the following table after choosing an element using a jQuery selector?

I'm looking for a selector that can start at the element I click on and locate the next item with a specific class on the page. Here's an example to illustrate my request: <table> <tr> <td>Some text here</td> <td>&l ...

Bootstrap CSS: arranging columns for mobile devices

UPDATE: Having implemented the solution provided in the accepted answer below, I find myself back at square one with the original layout before any adjustments were made. The issue still remains unresolved. Any advice on how to achieve the desired design o ...

Utilizing jQuery's multiple pseudo selectors with the descendant combinator to target specific elements

My code includes the following: <div class="a"><img></div> and <div class="b"><img></div> I want to dynamically enclose img tags with a div and utilize $(":not('.a, .b) > img") for ...

React component failing to update upon rerender

I've encountered an issue with my Flux setup where the component doesn't rerender when adding a new Todo, although it does when deleting or changing the checkbox. I find this behavior confusing and wonder what might be causing it. The list itself ...

What is the best way to synchronize the state of a single React component across various pages?

I am currently working on a React Component that includes a toggle feature (on or off) with the state being managed by the component's own state (this.state). My dilemma is ensuring that this state remains when the user navigates from one page to ano ...

What is the best approach to transforming my jQuery function into CSS to ensure responsiveness?

I have created a jQuery animation with four functions named ani1(), ani2(), ani3(), and ani4(). Everything is working fine on desktop, but now I am facing the challenge of making it responsive for mobile devices. I am looking for CSS code to replicate the ...

The Datatable fails to render the JSON data

Currently, I am dynamically binding a DataTable from a JSON URL and also generating headers dynamically. However, I am facing some issues in passing the JSON data to aaData in the DataTable. Can you please take a look at my code snippet below and provide m ...

Activate just the show more / show less button on the website that has several buttons with identical ids

Whenever the "show more" button is clicked, additional images are displayed in the gallery and the button text changes to "show less". However, in my ExpressionEngine (CMS) templates and entries, all "show more" buttons share the same id, causing other but ...

My pen doesn't accurately display the ID

CHALLENGE var shoppingCenters = [{ id: 0, name: 'Leclerc', location: 'Paris,France', address:'Boulevard Rahal El Meskini Casablanca Maroc', ] }, { /*Malls B*/ id: 1, name: 'Carefour', location ...

Deactivating a Vue custom filter when hovering over it

I'm trying to figure out how to disable a truncate filter when hovering over an element using VueJS 2. Here's the part of my template that includes the filter: <div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div> ...

Implement the parent jQuery library within a child iframe

I have a query regarding the use of two iframes in my HTML page. I am trying to implement a single jQuery file that is loaded on the parent page. The code snippet provided below works perfectly on all browsers, except for one issue with Chrome when using t ...

Retrieve the file from Amazon S3 and download it

I'm having an issue with downloading a file from a directory outside of the root. Whenever I try, it defaults to looking in the root directory. I need users to be able to download these files on my site. The file was initially uploaded to Amazon S3 a ...

Tips for creating a stylish, blurred, and centered box for a login form on a full-size background that is also responsive

I attempted to create a login form on an HTML page using Angular, featuring a full-size background image that is centered. The form itself is contained within a div with a blurred background, also centered both horizontally and vertically within the browse ...