9

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

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
user291701
  • 38,411
  • 72
  • 187
  • 285

4 Answers4

11

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
  • 6,389
  • 6
  • 33
  • 53
  • 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 Oct 09 '10 at 02:04
4

You could do this:

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

Also, look here: jQuery animate backgroundColor (same issue, lot's of answers)

Community
  • 1
  • 1
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
2

This question is very old; but for anyone who needs an even better solution; see:

http://jsfiddle.net/kSgqT/

It uses Jquery and CSS3 to toggle a class whilst fading the class in :-)

The HTML:

<div class="block" id="pseudo-hover">Hover Me</div>

<div class="block" id="pseudo-highlight">Highlight Me</div>

The JavaScript

$('#pseudo-hover').hover( function() {
    $('#pseudo-highlight').toggleClass('highlight');
});
Miller
  • 34,962
  • 4
  • 39
  • 60
Matt
  • 2,450
  • 5
  • 30
  • 36
1

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
  • 56,972
  • 13
  • 121
  • 140