I'm trying to log my colors variable after the forEach block completes execution.
As the code stands now it simply returns an empty array. I guess I'm not console.logging at the right moment, but I'm confused about when that should happen.
Basically, what I need is to be able to use my colors array to execute other functions on it. But before I do that I have to make sure that the createParentComponent function finished executing.
Thanks in advance!
var colors = [];
function createParentComponent(array){
var count = 0;
array.forEach(function(image){
var parent = document.createElement('div');
parent.style.height = '50px';
parent.style.width = '50px';
parent.className = 'parent';
var imgData = createImgandColorDiv(image);
var img = imgData[0];
var cdiv = imgData[1];
parent.appendChild(img);
parent.appendChild(cdiv);
document.getElementById('container').appendChild(parent);
count ++;
console.log(count);
});
if(count === array.length){console.log(colors);}
}
function createImgandColorDiv(url){
var img = document.createElement('img');
img.style.height = '50px';
img.style.width = '50px';
var cdiv=document.createElement('div');
cdiv.style.height = '50px';
cdiv.style.width = '50px';
cdiv.className = 'cdiv';
img.onload = function(){
var hsl = getDominantHSLColor(img);
colors.push(hsl);
cdiv.style.backgroundColor = 'hsl('+hsl[0]+','+hsl[1]+'%,'+hsl[2]+'%)';
};
img.src = url;
return [img, cdiv];
}
I was trying to inspire myself from this.