Fade in / fade out background color of an HTML element with Javascript (or jQuery)

Here's what I cooked up. It works nicely without the need of any UI library. Even jQuery can be eliminated if needed.

//Color row background in HSL space (easier to manipulate fading)
$('tr').eq(1).css('backgroundColor','hsl(0,100%,50%');

var d = 1000;
for(var i=50; i<=100; i=i+0.1){ //i represents the lightness
    d  += 10;
    (function(ii,dd){
        setTimeout(function(){
            $('tr').eq(1).css('backgroundColor','hsl(0,100%,'+ii+'%)'); 
        }, dd);    
    })(i,d);
}

Demo : http://jsfiddle.net/5NB3s/2/

  • SetTimeout increases the lightness from 50% to 100%, essentially making the background white (you can choose any value depending on your color).
  • SetTimeout is wrapped in an anonymous function for it to work properly in a loop ( reason )

One way could be :

JS :

$('tr').eq(1).hide().addClass('success').fadeIn('slow');

setTimeout(function(){
  $('tr').eq(1).fadeOut('slow',function(){ $(this).removeClass('success').show();});
},2000);

Bootply : http://www.bootply.com/123956


UPDATE Second way, much better, but... I'll explain :

Bootply : http://www.bootply.com/123956 [still the same url don't worry]

JS :

$('tr').eq(1).animate({
  backgroundColor: "#dff0d8"
}, 2000 );


setTimeout(function(){
        $('tr').eq(1).animate({
          backgroundColor: "#ffffff"
        }, 2000 );
},2000);

You have to use jQueryUI animate and the result it's visually good...


I had the same problem and couldn't find an easy way to do it other than programming. Another way to achieve fadding BG colors is using CSS properties for each row when hovering them.

#RowID{
background-color: #ececec;
background-color: rgba(236, 236, 236, 0.901961);
-moz-transition: background-color 1s cubic-bezier(1,1,1,1);
-moz-transition-delay: 0.5s;
-ms-transition: background-color 1s cubic-bezier(1,1,1,1);
-ms-transition-delay: 0.5s;
-o-transition: background-color 1s cubic-bezier(1,1,1,1);
-o-transition-delay: 0.5s;
-webkit-transition: background-color 1s cubic-bezier(1,1,1,1);
-webkit-transition-delay: 0.5s;
transition: background-color 1s cubic-bezier(1,1,1,1);
transition-delay: 0s;
}

#RowID:hover {
    background-color: rgb(206, 128, 128);
} 

In addition you can always set the delay you want for the BG to change setting the transition-delay property.

JSFiddle