0

Hello I am a self taught developer and I am trying to use a for() loop with jQuery, but it does not seem to work. I am trying to loop through an array of RGB colors, that are hard coded for now with strings. Here is a snippet below on what I am trying to accomplish. I want each div to contain a diffrent

http://jsfiddle.net/CleverOscarDev/cyztq6m5/

var squares = $(".squares");
var colors = [
  "rgb(255, 0, 0)",
  "rgb(0, 255, 0)",
  "rgb(0, 0, 255)",
  "rgb(255, 0, 0)",
  "rgb(255, 0, 0)",
  "rgb(255, 0, 0)",
]

for (var i = 0; i < squares.length; i++) {
  squares[i].style.backgroundColor = colors;
}
1
  • This line squares[i].style.backgroundColor = colors is assigning the whole array. Instead, you should assign color[i] Commented Aug 31, 2018 at 4:48

5 Answers 5

7

Check the updated fiddle http://jsfiddle.net/0xdwhsnc/

You missed the index, instead of colors use colors[i]

for (var i = 0; i < squares.length; i++) {
 squares[i].style.backgroundColor = colors[i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

more specific : colors[i % colors.length]
1

Try each loop. http://jsfiddle.net/cyztq6m5/15/

$(squares).each(function(key, value) {
  value.style.backgroundColor = colors[key];       
}); 

Comments

1

If your colors array is going to have same number of colors as the number of div.s with class square you can do this!

$(".squares").each(function(key, value) {
    $(this).css({"background-color" : colors[key]});
});

2 Comments

You're setting on each iteration a given color for all squares at the same time
Updated the answer. thanks for the heads up @RobertoMaldonado
0

You got a simple error, colors is an array, not a color string, so you should use colors[i]

for (var i = 0; i < squares.length; i++) {
  squares[i].style.backgroundColor = colors[i];
}    

Comments

0

you can also use jquery for each

$.each(squares, function(idx, square){
    square.style.backgroundColor=colors[idx]
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.