Lieutenant Dan
Lieutenant Dan

Reputation: 8274

implement a transition effect between addClass and removeClass

$('.greenBox').hover(function(){
    $(this).addClass('expanded');
    $(this).removeClass('contracted');
}, function(){
    $(this).removeClass('expanded');
    $(this).addClass('contracted');
}); // end of hover state for green box

Wondering if there is a way to implement a transition with the above jquery logic? Between the adding or removing of the class.

I have tried the below, but it did not work: (It is a simple div small height > large height toggle)

.expanded {
    height: auto;
    // to make the box move up add back the bottom 300px
    // bottom: 300px;
    background: linear-gradient(#812990, #9e248e);
    -webkit-transition-timing-function: linear; 
    transition-timing-function: linear; 
}

also:

.contracted {
    height: 100px;
}

Upvotes: 0

Views: 107

Answers (2)

sheriffderek
sheriffderek

Reputation: 9043

It seems like you can simplify the JavaScript and only have one class that you toggle. You can't use CSS to animate to auto, because it's not aware of what that means, but you can trick it with max-height... You'll have to just be arbitrary and get closest to the common size. Otherwise you'll have to use jQuery animate (or velocity) and query the height so you know what integer to animate to - and then leave the CSS transition out.

jQuery

$('.greenBox').hover( function() {
    $(this).addClass('expanded');
}, function() {
    $(this).removeClass('expanded');
});

CSS

.greenbox {
  height: 864572px;
  max-height: 100px;
  transition: .2s; 
}

.greenbox.expanded {
  max-height: 500px
}

jsFiddle

Upvotes: 0

Shaggy
Shaggy

Reputation: 6796

Apply the transition to your .greenbox class, rather than either of the 2 you're adding & removing:

.greenbox{
    transition:height .5s linear;
}

Having said that, you cannot transition to or from an auto value in CSS so, the trick you would want to use here is to instead set the max-height of the expanded class to a value greater than the height its contents can ever be and transition that, instead.

.greenbox{
    transition:max-height .5s linear;
}
.contracted{
    max-height:100px;
}
.expanded{
    max-height:1000px;/* adjust to suit your content */
}

Depending on the value you set for the larger max-height, you may need to tweak the timing of the transition to improve how it looks.

Incidentally, you could achieve this entirely with CSS with absolutely no need for any JavaScript, like so:

.greenbox{
    max-height:100px;
    transition:max-height .5s linear;
}
.greenbox:hover{
    max-height:1000px;/* adjust to suit your content */
}

Upvotes: 2

Related Questions