user291701
user291701

Reputation: 39671

Fade a class in?

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

Upvotes: 9

Views: 16016

Answers (4)

Matt
Matt

Reputation: 2611

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');
});

Upvotes: 2

Peter Ajtai
Peter Ajtai

Reputation: 57685

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

Upvotes: 1

Alexis Abril
Alexis Abril

Reputation: 6459

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.

Upvotes: 11

Šime Vidas
Šime Vidas

Reputation: 185893

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)

Upvotes: 4

Related Questions