40

I can animate from transparent to color, but when I tell jquery to animate the backgroundColor: 'transparent' it just changes to white. Any idea how to fix this?

jonstjohn
  • 59,650
  • 8
  • 43
  • 55

12 Answers12

22

Transparent isn't really a color. So, you can't animate to it. You might be able to achieve the effect you're looking for by using a separate element for the background, and animating the opacity though.

Example:

HTML:

<body style="background-color:yellow">
  <!-- by default, "see through" to parent's background color -->
  <div id="container"> 
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    Aenean nec magna. Nulla eu mi sit amet nibh pellentesque vehicula. 
    Vivamus congue purus non purus. Nam cursus mollis lorem.    
  </div>
</body>

Script:

// on load...
$(function()
{
  var container = $("#container");
  container
    .hover(
      // fade background div out when cursor enters, 
      function() 
      { 
        $(".background", this).stop().animate({opacity:0}); 
      }, 
      // fade back in when cursor leaves
      function() 
      { 
        $(".background", this).stop().animate({opacity:1}) 
      })
    // allow positioning child div relative to parent
    .css('position', 'relative')
    // create and append background div 
    // (initially visible, obscuring parent's background)
    .append( $("<div>")
      .attr('class', 'background')
      .css({
        backgroundColor:'blue',
        position: 'absolute',
        top:0,
        left:0,
        zIndex:-1,
        width:container.width(), 
        height:container.height()
      }) 
    );
});

Kingjeffrey's comment points out that this answer is somewhat outdated - browsers do now support RGBA color values, so you can animate just the background. However, jQuery doesn't support this in core - you'll need a plugin. See also: jQuery + RGBA color animations

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
  • 12
    Your statement "Transparent isn't really a color" may be true in color theory, but it is not accurate when describing how browsers handle the 'transparent' keyword. Browsers treat 'transparent' as black with 0% opacity. This becomes particularly important when working with gradients. If you create a CSS3 gradient between white and transparent, you will see some grey creeping in (because it transitions the color to black and the opacity to 0). To avoid the unwanted grey, set your gradient for white to rgba(255,255,255,0). – kingjeffrey Apr 28 '11 at 06:30
11

I wanted to do this and since I couldn't find it, I hacked it together. This is only for white, suit to your needs:

function animate_bg(ele, from, to) {
    ele.css("background-color", "rgba(255, 255, 255, " + (from += from > to ? -1 : 1) / 10 + ")"); 
    if(from != to)  
        setTimeout(function() { animate_bg(ele, from, to) }, 20);
}

Usage:

$("a").hover(
    function() {return animate_bg($(this), 0, 10)},
    function() {return animate_bg($(this), 10, 0)}
);

Linus Thiel
  • 38,647
  • 9
  • 109
  • 104
8
$(selector)
    .css({backgroundColor:"#f00"})
    .animate({backgroundColor:"transparent"}, 2000, null, 
    function() { this.style.backgroundColor='transparent'; });

Not as clean because it fades the bg to white before making it transparent, but it's an option.

Jeff Atwood
  • 63,320
  • 48
  • 150
  • 153
lucky760
  • 81
  • 1
  • 1
5

You can use rgba(61, 31, 17, 0.5) color where 0.5 is the opacity. Then if you want transparent set the opacity to 0.0

$('.myClass').animate({ "backgroundColor" : "rgba(61, 31, 17, 0.0)" }, 1000);
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
Merlin
  • 4,907
  • 2
  • 33
  • 51
  • if the starting color already has some reduced opacity (e.g. a rgba(255,255,255,.2) by default in the CSS, velocity is stuck with this opacity and rgba won't change anything – Ben Jul 31 '14 at 10:24
  • This is the answer, simple and neat. The jQuery [.animate](http://api.jquery.com/animate/) function has exactly such purpose, considering that it serves to "performe a custom animation of a set of CSS properties", on the present case, on the `background-color`. – João Pimentel Ferreira Jul 28 '18 at 10:27
  • you should also mention that you need an extra jquery plugin: https://github.com/jquery/jquery-color – João Pimentel Ferreira Jul 28 '18 at 10:33
2

Use CSS transition:

$('smth').css('transition','background-color 1s').css('background-color','transparent')

or

$('h1').css({'transition':'background-color 1s','background-color':'red'})
Dimava
  • 7,654
  • 1
  • 9
  • 24
2

I used the answer of Linus but ran into IE. Changed it about a bit to work in IE as well:

function animate_bg(ele, from, to) {
    from += from > to ? -1 : 1;
    if(!$.support.opacity){
        if(from != to){
            var opStr = (Math.round(from * 25.5)).toString(16);
            //alert(opStr)
            ele.css({background:'transparent',filter:"progid:DXImageTransform.Microsoft.gradient(startColorstr=#" + opStr + "FFFF00, endColorstr=#" + opStr + "FFFF00)"});   
        }else{
            ele.css({background:'transparent',filter:"none"});   
        }
    }else{
        ele.css("backgroundColor", "rgba(255, 255, 0, " + (from) / 10 + ")"); 
    }

    if(from != to)  
        setTimeout(function() { animate_bg(ele, from, to) }, 50);
}

Usage is the same:

$("a").hover(
    function() {return animate_bg($(this), 0, 10)},
    function() {return animate_bg($(this), 10, 0)}
);
Maarten Wolzak
  • 2,651
  • 1
  • 19
  • 18
1

Use jQuery Color plugin: https://github.com/jquery/jquery-color

It will get your transparent as well as rgba animations working properly.

Ondrej Machulda
  • 998
  • 1
  • 12
  • 24
1

I changed Shog9's code a bit to fit my needs. It's sort of like the jQuery UI Highlight, only it does not fade into white. It's not perfect, but it works on most elements

function highlight(element, color, speed) {
if (speed == null) speed = "fast";
var e;
var position;
element.each(function() {
    e = $(this);
    position = e.css('position');
    if (position != 'absolute')
        e.css('position', 'relative');
    log(position);
    e.append($("<div>")
        .css({
            backgroundColor: color,
            position: 'absolute',
            top: 0,
            left: 0,
            zIndex: -1,
            display: "none",
            width: e.width(),
            height: e.height()
        }).fadeIn(speed).fadeOut(speed, function() { $(this).remove(); e.css('position', position); })

      );
}); }
Contra
  • 2,754
  • 4
  • 20
  • 18
1

You have to chain it.

For example, you can't do this:

$('#panel').animate({'backgroundColor' : 'rgba(255,255,0,0.7', 'opacity': 1}, 3000);

or even

$('#panel').animate({'background-color' : 'yellow', 'opacity': 1}, 3000);

but you can do this:

$('#panel').css('background-color', 'rgba(255,255,0,0.7)').animate({'opacity': 1}, 3000);
kleopatra
  • 51,061
  • 28
  • 99
  • 211
Matt
  • 43
  • 1
  • 7
1

I used the function parameter to remove the style after the animation was done:

$('[orgID=' + orgID + 'bg]').animate({ backgroundColor: "white" }, 300, "linear", function()
 {
     $('[orgID=' + orgID + 'bg]').css('background-color', '');
});

It worked great.

Porter
  • 11
  • 1
0

My solution was to animate to the colour seen by the user (ie. the colour of the parent element), and then set to the original colour (which may or may not be 'transparent') once the animation is finished

var $t = $(some selector);

var seenColour = findColour($t, 'background-color');
var origColour = $t.css('background-color');
$t.css('background-color', '#ffff99');
$t.animate(
    {backgroundColor: seenColour}, 
    4000, 
    function(){ $t.css('background-color', origColour)}
);

function findColour($elem, colourAttr)
{
    var colour = $elem.css(colourAttr);
    if (colour === 'transparent')
    {
        var $parent = $elem.parent();
        if ($parent)
        {
            return findColour($parent, colourAttr);
        }
        // Default to white
        return '#FFFFFF'; 
    }
    return colour;
}
AaronHolland
  • 1,595
  • 1
  • 16
  • 32
0

Use background instead of backgroundColor:

$('#myDiv').animate({background: "transparent"});
user2755541
  • 536
  • 2
  • 10
  • 25