Reputation: 77
I am have created an array of colors. I am trying to use colors.forEach inside ready function to call addBox for each color in this array. The plan is that I see that all the colors have been added when the page is reloaded. Let me know if you need html code pls
function addBox(color) {
$('#colors').prepend('<div class="item" style="background-color: ' + color + ';"></div>');
}
var colors = ['22ac5e', 'd68236', '770077'];
// I think my problem lies after this line
$(document).ready(function () {
// var colors = ['22ac5e', 'd68236', '770077'];
colors.forEach(addBox(color))
});
Many thanks in advance.
Upvotes: 0
Views: 29
Reputation: 337580
You're providing the result of addBox(color)
to the forEach()
loop, you're not actually providing the reference of that function so it can be called.
There's a couple of ways you can amend your code so that it will work. Firstly, an anonymous function:
colors.forEach(function(color) {
addBox(color)
});
Or an arrow function if you don't need IE support at all:
colors.forEach(color => addBox(color));
Finally note that the hex colours in your CSS will need the #
prefix:
'... style="background-color: #' + color + ';" ...'
Upvotes: 3