Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuously animate element's background

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?

like image 538
XeeMez AsHu Avatar asked Dec 01 '22 03:12

XeeMez AsHu


1 Answers

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 the vendor prefixes

Update

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

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

});
like image 50
Ahmad Alfy Avatar answered Dec 04 '22 10:12

Ahmad Alfy