Reputation: 3
I have been trying to find away to alternate the background color of a div. I have 11 total colors and need to cycle through them with out having the same color show up twice in a row. I have looked at the nth-child in css with no avail end up with all the same color in a few rows. Now i am trying to do it via for loops in javascript. Does any one know of a easier way to this? I have this and its gone through many iterations. I am just stuck at this point.
function ColorChange(){
var divcount = $('.time').length;
var timediv = document.getElementsByClassName('time');
var mycolors = new Array("#0066cc","#996699","#990033","#ff9933", "#99cc33","#33cc66","#009999","#6699cc", "#999999","#534741", "#663333");
for(var i = 0; i<timediv.length; i++){
for(var l = 0; l<mycolors.length;l++){
timediv[i].style.background = mycolors[l];
}
}
}
Upvotes: 0
Views: 87
Reputation: 12717
Another option is a pure css route: http://jsfiddle.net/bhlaird/9Hbmr/
#colors .time:nth-child(11n) {
background-color:#0066cc;
}
#colors .time:nth-child(11n+1) {
background-color:#996699;
}
#colors .time:nth-child(11n+2) {
background-color:#990033;
}
#colors .time:nth-child(11n+3) {
background-color:#ff9933;
}
etc
Upvotes: 0
Reputation: 17361
You could create a utility class to aid with the cycling.
Here's an example of such a class. You can pass it an array and cycle through it endlessly by calling next()
.
function Cycler (collection) {
this.collection = collection;
this.index = 0;
this.next = function () {
if (this.index >= this.collection.length) {
this.index = 0;
}
return this.collection[this.index++];
}
}
var mycolors = new Array("#0066cc","#996699","#990033","#ff9933", "#99cc33","#33cc66","#009999","#6699cc", "#999999","#534741", "#663333");
var cycler = new Cycler(mycolors);
for (var i = 0; i < timediv.length; i++) {
timediv[i].style.backgroundColor = cycler.next();
}
Upvotes: 0
Reputation: 12717
You appear to be using a mix of jquery and javascript. So I went the jquery route
http://jsfiddle.net/bhlaird/NyKFf/
function ColorChange(){
var count = 0;
var mycolors = new Array("#0066cc","#996699","#990033","#ff9933", "#99cc33","#33cc66","#009999","#6699cc", "#999999","#534741", "#663333");
$('.time').each(function() {
$(this).css('background-color', mycolors[count++]);
if (count > mycolors.length) count = 0;
});
}
Upvotes: 0
Reputation: 324620
You appear to be effectively setting the background colour to the last colour in the list. Why not try this:
for( var i=0; i<timediv.length; i++) {
timediv[i].style.backgroundColor = mycolors[i % mycolors.length];
}
This will cycle through the defined colours, and thanks to the %
operator it will loop around to the start of your list if it goes past the end.
Upvotes: 3