I am using color-thief js to get the color of each image inside a div. I am trying to loop through each and retrieve colors. This works fine. In my console, it shows the colors for each image.
I have some extra code that converts the results, which are in RGB, to HEX. This also works fine in the console. My results are HEX colors for each image.
When I try to apply the HEX to a div, i always get the last color.
I understand what is going in, the loop keeps overriding itself, therefore returning the last color. I just don't know how to prevent this and on each loop apply the color to a div.
$(window).load(function() {
var color_thief = new ColorThief();
$('.thumbnail-image-link img').each(function() {
var dominant_color = color_thief.getPalette(this, 2);
// Converts RGB to HEX
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function rgbToHex(r, g, b) {
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
var colorOne = rgbToHex(dominant_color[0][0], dominant_color[0][1], dominant_color[0][2]);
console.log("Hex One " + colorOne);
var colorTwo = rgbToHex(dominant_color[1][0], dominant_color[1][1], dominant_color[1][2]);
console.log("HEX Two " + colorTwo);
//This is where my issue is
$(".section").css('background', colorOne);
});
});
Edit: Added HTML Code.
Edit 2: Took out extra div to avoid confusion.

Basically, I need to add a background color to each .section as it loops.
Loop Start //depending how many images the for.each returns.
-container -> value from loop 1 results
-container -> value from loop 2 results
-container -> value from loop 3 results
-container -> value from loop 4 results
Loop End
Thanks again!
In your
$('.thumbnail-image-link img').eachloop, save the index of the current element you're iterating over by defining the first argument of theeachcallback. Then you can use.eqto select the correct.sectionelement, and set its CSS:and then