0

I want to animate background from coloured to transparent. I have code like this:

$('.selector')
.animate({
        'background-color' : 'transparent'
}, 2000, function () {
        $(this).css({ 'background-color' : '' });
});

It is quite complicated, because:

  1. I need to remove the style="" after the animation finishes, because otherwise the style would keep overriding the CSS class set by the .hover handler. So I used this trick: jQuery - remove style added with .css() function

  2. I don't know of any neater way to wait for effects to complete in jQuery, see: How to wait for effect queue to complete in jQuery call sequence

So, is there any simpler solution? Some more clever use of jQuery effects which wouldn't be so complicated?

I also tried the trick with .animate(,1):

$('.selector')
.animate({
        'background-color' : 'transparent'
}, 2000)
.animate({'background-color': ''}, 1);

but it doesn't work in this case.

Community
  • 1
  • 1
Tomas
  • 57,621
  • 49
  • 238
  • 373

2 Answers2

1

css

.animated {-webkit-transition:background 0.4s ease;-moz-transition:background 0.5s ease;-ms-background 0.5s ease;background 0.5s ease;}
.selector {background:red}
.transparent_background {background: transparent};

html

<div class="selector animated"></diV>

js

$(".selector").addClass("transparent_background");

http://jsfiddle.net/UEyc6/

enapupe
  • 15,691
  • 3
  • 29
  • 45
1

Let CSS do the animation, and fallback to javascript when it's not supported with (for example) Modernizr: http://modernizr.com/

if (Modernizr.csstransitions) {
    // Animate background color
    $('.element').addClass('animate-background-color');
} else {
    // use javascript animation.
}

And Your css:

.element {
    -webkit-transition: background-color .5s ease-out 0.1s;
    -moz-transition: background-color 5s ease-out 0.1s;
    transition: background-color .5s ease-out 0.1s;
    background-color: rgba(121,123,123,1);
}

.element.animate-background-color {
    background-color: rgba(121,123,123,0);
}

Fiddle for the css animation: http://jsfiddle.net/c5PHf/

Rick Lancee
  • 1,629
  • 1
  • 15
  • 20
  • @TMS thats what Modernizr is for, it checks the support. If its not supported you fallback to javascript animations. Heres the support: http://caniuse.com/#search=css%20transition – Rick Lancee Apr 17 '14 at 20:04