How do I dynamically change the color of an element?
How can I change the colors of elements using variables?
Let's say we have four lines (colors). I need to give each element of the class a different, 1,2,3,4,1,2,3 ... and so on:
function pressLineColors() {
var a = "#eee",
b = "#123",
c = "#fff",
d = "#ae23e5";
$('.pressLine').each(function (i) {
//go througt each of this, and give them colors, so when new elements
// appear, give them next color.
});
}
The first sholud element has color a , second b , third c , fourth d and fifth a , ...
source to share
function pressLineColors() {
//setup array of colors and a variable to store the current index
var colors = ["#eee", "#123", "#fff", "#ae23e5"],
curr = 0;
//loop through each of the selected elements
$.each($('.pressLine'), function (index, element) {
//change the color of this element
$(this).css('color', colors[curr]);
//increment the current index
curr++;
//if the next index is greater than then number of colors then reset to zero
if (curr == colors.length) {
curr = 0;
}
});
}
Here's a demo: http://jsfiddle.net/SngJK/
Update
You can also use the suggestion in the comments to this answer to shorten the code a bit:
function pressLineColors() {
var colors = ["#eee", "#123", "#fff", "#ae23e5"],
len = colors.length;
$.each($('.pressLine'), function (index, element) {
$(this).css('color', colors[index % len]);
});
}
Here's a demo: http://jsfiddle.net/SngJK/2/
Update
You can also use .css('color', function (){})
to iterate over each of the elements, returning the color you want to create:
$('.pressLine').css('color', function (index, style) {
return colors[index % len];
});
Here's a demo: http://jsfiddle.net/SngJK/4/
source to share
Create a variable to track, and a separate function will allow you to add items later and track
/* colors in indexable array*/
var colors=["#eee", "#123","#fff","#ae23e5"];
var counter=0;
$('.pressLine').each(function () {
$(this).css('color', colors[nextColorIndex()]);
});
function nextColorIndex(){
var ctr=counter;
counter=(++counter <colors.length) ? counter++ :0
return ctr;
}
source to share
you need to put your list in an array-like object and then access by index;
function pressLineColors() {
var colors = [ a = "#eee",
b = "#123",
c = "#fff",
d = "#ae23e5"];
$('.pressLine').each(function (i) {
//go througt each of this, and give them colors, so when new elements
// appear, give them next color.
$(this).css("color" , colors[i]);
});
}
source to share