NeuTronas NeuTronas - 20 days ago 5
jQuery Question

CSS3 transition animation when adding/removing class in child elements

I have a problem that CSS3 transitions doesn't work on child elements when adding a class to a parent.

Here's my code:
http://jsfiddle.net/4zwg3/327/

Image doesn't get animations and instantly goes to 50px height.

CSS:

.header {
height: 400px;
width: 400px;
background: blue;
}

.small_header img {
height: 50px;
background-size: auto 100%;
-webkit-transition: all 1.7s ease;
transition: all 1.7s ease;
}

.small_header {
height: 100px;
background-size: auto 100%;
-webkit-transition: all 1.7s ease;
transition: all 1.7s ease;
}


HTML:

<div class="header">
<img src="http://www.codeproject.com/KB/GDI-plus/ImageProcessing2/img.jpg">
</div>


Javascript:

var click = 1;

$( ".header" ).on( "click", function() {
console.log('works');
if (click == 1) {
$(".header").addClass("small_header");
$(".small_header").removeClass("big_header");
click = 0;
} else {
$(".header").addClass("big_header");
$(".small_header").removeClass("small_header");
click = 1;
}
});


But as you can see there's no transition animations on image.

How can it be fixed?

Answer

This issue because the image doesn't have any start height and browser can't calculate the transition, and if you add transition on the small_header class, the transition works only when the image shrinks.

$( ".header" ).on( "click", function() {
    $(".header").toggleClass("small_header");
});
.header {
  height: 400px;
  width: 400px;
  background: blue;
}

.header img {
  height:200px;
  -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}

.small_header img {
    height: 50px;
    background-size: auto 100%;    
}

.small_header {
    height: 100px;
    background-size: auto 100%;    
    -webkit-transition: all 1.7s ease;
    transition: all 1.7s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<img src="http://www.codeproject.com/KB/GDI-plus/ImageProcessing2/img.jpg">
</div>

Comments