First off, altering a div's background-color
necessitates changing its CSS background-color
property. How else could it be done?
If your goal is to retain the last background color (for a specific action or to revert back to it later), then store it in hidden input variables.
Afterwards, you can utilize these values wherever needed.
Furthermore, if you wish to extract the background-color
property and showcase it as text within the div, it can be achieved effortlessly.
var color = $('#selector').css('backgroundColor');
, however this will provide the RGB value. For hex representation, employ the following convenient methods:
var hexDigits = new Array
("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f");
//Function to convert hex format to an RGB color
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function hex(x) {
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}
referenced from here
Update,
Your current divs
are structured like this:
<div id="a1" class="card"></div>
<div id="a2" class="card"></div>
<div id="a3" class="card"></div>
..
..
Given that you intend to assign a unique color to each of these divs, modify them using JavaScript within your loop to resemble this:
<div id="a1" class="card" data-color-index="1"></div>
<div id="a2" class="card" data-color-index="2"></div>
<div id="a3" class="card" data-color-index="3"></div>
Now, when clicking on a specific div, retrieve its index and select the corresponding item from your colors
array. Since you are modifying the original array using splice
, I created a duplicate for future usage.
You can access any element's attribute data-color-index
via jQuery as demonstrated below:
$('#selector').data('color-index');
View this snippet. It accomplishes the desired functionality.