0

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.

Othello
  • 55
  • 11
  • Possible duplicate of [Calling functions with setTimeout()](https://stackoverflow.com/questions/3800512/calling-functions-with-settimeout) Although you are not using `setTimeout` explicitly, the answer is the same; put the callback in there without parentheses. – Heretic Monkey Jun 08 '18 at 21:23
  • The online tutorial that I am using doesn't cover setTimeout(). I do apologise for the similarities or overlap in topic covered. – Othello Jun 16 '18 at 08:51

1 Answers1

3

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 + ';" ...'
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339