Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a table whose row needs to be highlighted & then cleared. I'm using contextual classes to color the table rows (not a necessary requirement). The javascript part is given below. How can I animate i.e. fadeIn / fadeOut the coloring of rows using javascript / jQuery / Bootstrap. The code below instantly adds & removes the color.

$('tr').eq(1).addClass('success');

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

http://jsfiddle.net/5NB3s/

P.S. Trying to avoid the jQuery UI route here How do you fade in/out a background color using jquery?

like image 338
user Avatar asked Mar 22 '14 18:03

user


People also ask

How do I fade a color in Javascript?

The jQuery fadeOut() method is used to fade out a visible element. Syntax: $(selector). fadeOut(speed,callback);

What is the use of fadeOut in jQuery?

The fadeOut() method gradually changes the opacity, for selected elements, from visible to hidden (fading effect). Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: This method is often used together with the fadeIn() method.

What is fadeIn fadeOut effect?

The Fade In/Fade Out behavior lets you dissolve into and out of any object by ramping the opacity of the object from 0 percent to 100 percent at the start, and then back to 0 percent at the end. You can eliminate the fade-in or fade-out effect by setting the duration of the Fade In Time or Fade Out Time to 0 frames.


1 Answers

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 )
like image 50
user Avatar answered Oct 13 '22 01:10

user