Reputation: 390
I need to change the background-color of multiple elements at the same time. I tried several versions of this code:
var indexNumber = 0;
function colorChange(){
var colors = ["#0e76bd", "#aa43a0" ,"#5ad1e3"];
//var randColor = colors[Math.floor(Math.random()*colors.length)];
$('a, h1, h2, .subhead').animate({'color':colors[indexNumber]}, 1000);
$('.splash, .active').animate({'background-color':colors[indexNumber]}, 1000);
}
setInterval(function() {
colorChange()
indexNumber++
if (indexNumber == 3)
{indexNumber = 0
}}, 1000);
This made the colors change, but rather than all the colors advancing to the next sequence in the array, I get a random result where all elements are different colors.
I want all of my elements to change to the same color at the same time. Is there an easy way to do this?
Upvotes: 1
Views: 1653
Reputation: 3369
You don't need jquery UI to do this.. use interval and css3 animation if you want to animate:
a, h1, h2, .subhead, .splash, .active { -webkit-transition:color 1s ease, background-color 1s ease; transition:color 1s ease, background-color 1s ease;}
var _index = 0, colors = ["#0e76bd", "#aa43a0" ,"#5ad1e3"];
setInterval(changeColor, 1000);
function changeColor() {
$('a, h1, h2, .subhead').css({ 'color': colors[_index] });
$('.splash, .active').css({'background-color':colors[_index]});
_index = (_index < colors.length-1) ? _index+1 : 0;
}
Upvotes: 0
Reputation: 193261
You cannot animate colors using default jQuery animation framework. From the documentation:
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used).
So the answer is if you want to use jQuery you should also add jQuery UI animation plugin. Take a look at this demo: http://jsfiddle.net/g3QR3/
Here is the jQuery color plugin.
Or instead you could use CSS transitions, that would not require another plugin.
var indexNumber = 0;
function colorChange() {
var colors = ["one", "two", "three"];
$('a, h1, h2, .subhead, .splash, .active').removeClass("one two three").addClass(colors[indexNumber]);
}
setInterval(function () {
colorChange()
indexNumber++
if (indexNumber == 3) {
indexNumber = 0
}
}
CSS:
.colors {
-webkit-transition: color 1s ease;
transition: color 1s ease;
}
.one {
color: #0e76bd;
}
...
Upvotes: 2