Reputation: 342
Is it possible to animate element's background color in loop?
For ex: If we have one <div>
which has background-color:red
and through jQuery I change it to background-color:blue
. Now I want it to toggle
between red and blue continuously.
How can I do it?
Upvotes: 4
Views: 4346
Reputation: 371
Check out this fiddle.. http://jsfiddle.net/SidJadeja/XqwDC/
Just called recursive functions to animate a toggle between red and blue colors continuously. You can modify the duration as per your needs.
JS:
function anim() {
$("body").animate({
backgroundColor: "darkblue"
}, {
duration: 5000,
complete: function () {
$("body").animate({
backgroundColor: "darkred"
}, {
duration: 5000,
complete: function () {
anim();
}
});
}
});
}
Upvotes: 1
Reputation: 13371
@keyframes epilepsy {
from {
background: red;
color:blue;
}
to {
background: blue;
color:red;
}
}
.element {
animation-duration: 0.1s;
animation-name: epilepsy;
animation-iteration-count: infinite;
animation-direction: alternate;
}
Note: I did not add the vendor prefixes
I went a little bit zealous and included fallback using jQuery and modernizr. Note that background-color transition is not supported in jQuery animate by default; jQuery color plugin is required
$(document).ready(function() {
// Using Modernizr to test if CSS transition is supported or not
if(!Modernizr.csstransitions){
setInterval(function() {
// Go really crazy and do the amazing voodoo using JavaScript
$('.default').animate({
backgroundColor: 'red',
color: 'blue'
}, 100).animate({
backgroundColor: 'blue',
color: 'red'
}, 100);
}, 100);
});
});
Upvotes: 11
Reputation: 32581
CSS
.divClassRed{
background-color:red;
}
.divClassBlue{
background-color:blue;
}
jQuery
setInterval(function(){
if($('#myDiv').hasClass('divClassRed')){
$('#myDiv').addClass('divClassBlue').removeClass('divClassRed');
}else{
$('#myDiv').addClass('divClassRed').removeClass('divClassBlue');
}
},1000);
Upvotes: 6
Reputation: 1915
Check out this JS fiddle http://jsfiddle.net/uU4gu/
setInterval(function () {
$('div').css("background-color", "yellow");
setTimeout(function () {
$('div').css("background-color", "red");
}, 1000);
}, 2000);
Upvotes: 1
Reputation: 8981
try this
var x;
function changecolors() {
x = 1;
setInterval(change, 1000);
}
function change() {
if(x == 1) {
color = "red";
x = 2;
} else {
color = "blue";
x = 1;
}
document.body.style.background = color;
}
Upvotes: 1