Reputation: 1309
How to alternate style (background color with jquery) for div inside div with id="container" alternately ( even and odd ) if I have HTML like this
<div id="container">
<div></div>
<div></div>
<div></div>
<div></div>
...
</div>
I know with table like
$('#container>div:odd').css("background-color", "#ff0000");
$('#container>div:even').css("background-color", "#00ff00");
but the all the [divs] should have different colours...?no div should have the same colour ..can any one help me..
Upvotes: 0
Views: 1065
Reputation: 2849
try this:
var colors = ["f00", "0f0", "00f", "ff0", "0ff", "f0f"];
$('#someid .bar').each(function(i) {
$(this).css('background-color', '#'+colors[i % colors.length]);
});
For random colors, you can use this:
function randomColor() {
return 'rgb('+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+')'
}
$('#someid .bar').each(function(i) {
$(this).css('background-color', randomColor());
});
Demo:
Upvotes: 6