tags:

views:

52

answers:

3
+4  Q: 

Fade a class in?

Hi,

I've got a <td>. It has a class applied which specifies a background color. Can I fade-in to a different class, which just has a different background color? Something like:

// css
.class1 {
  background-color: red;
}

.class2 {
  background-color: green;
}

$('#mytd').addClass('green'); // <- animate this?

Thanks

+2  A: 

You could do this:

$("#mytd").fadeOut(function() {
   $(this).removeClass("class1").addClass("class2").fadeIn();  
});

Also, look here: http://stackoverflow.com/questions/190560/jquery-animate-backgroundcolor (same issue, lot's of answers)

Šime Vidas
+4  A: 

jQueryUI extends the animate class for this reason specifically. You can leave off the original parameter to append a new class to your object.

$(".class1").switchClass("", "class2", 1000);

Sample here.

Alexis Abril
The effect is not very pretty ==> http://jsfiddle.net/eKpem/ ----- Using two divs seems to be a little smoother ==> http://jsfiddle.net/Y4JNU/ ------ though it's close! (I think red to green is not the best choice ;) )
Peter Ajtai
A: 

You could put a clone on top of it and fade the original out while fading the clone in.

After the fades are done, you could switch back to the original element... make sure to do this in the fades callback!

The example code below will keep fading between the two classes on each click:

$(function(){
    var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();       

      // Create clone w other bg and position it on original
    $elie.toggleClass("class1, class2").appendTo("body")
         .offset({top: os.top, left: os.left}).hide();

    $("input").click(function() {

          // Fade original
        $mytd.fadeOut(3000, function() {
            $mytd.toggleClass("class1, class2").show();
            $elie.toggleClass("class1, class2").hide();            
        });
          // Show clone at same time
        $elie.fadeIn(3000);
    });
});​

jsFiddle example


.toggleClass()
.offset()
.fadeIn()
.fadeOut()

Peter Ajtai