Continuously animate an element's background

Is it possible to animate the background color of an element in a loop?

For example: if we have a <div> that has background-color:red , and through jQuery I change it to background-color:blue . Now I want it toggle between red and blue continuously .

How can i do this?

+4
source share
5 answers

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); 

Demo

+6
source

Y U NO DUDE

 @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; } 

Working demo

Note : I did not add provider prefixes.

Update

If we could get it to work on older browsers, that would be great!

I was a bit zealous and turned on jQuery and . Note that background color transition is not supported in jQuery aimate by default; jQuery color plugin 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); }); }); 
+11
source

try it

 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; } 
+1
source

Check out this JS script http://jsfiddle.net/uU4gu/

 setInterval(function () { $('div').css("background-color", "yellow"); setTimeout(function () { $('div').css("background-color", "red"); }, 1000); }, 2000); 
+1
source

Check out this fiddle .. http://jsfiddle.net/SidJadeja/XqwDC/

Simply called recursive functions for continuous animation of switching between red and blue colors. You can change the duration to suit your needs.

JS:

 function anim() { $("body").animate({ backgroundColor: "darkblue" }, { duration: 5000, complete: function () { $("body").animate({ backgroundColor: "darkred" }, { duration: 5000, complete: function () { anim(); } }); } }); } 
+1
source

Source: https://habr.com/ru/post/1487831/


All Articles