Fade a class in?

16k views Asked by At

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

4

There are 4 answers

0
Peter Ajtai On BEST ANSWER

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()

0
Matt On

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');
});
0
Šime Vidas On

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)

1
Alexis Abril On

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.