1

The following code does not behave as I expect in spite of the use of transition so there may be something I don't get about them.

Ideally, clicking on the button would append a child to the id2 div and make the id1 div grow smoothly accordingly.

$(function() {
  $("#id1 button").click(() => {
    $("#id2").append("<div class='child'>hehe</div>")
  });
});
#id1 {
  width: 100%;
  transition: all 2 ease;
}

.child {
  background-color: lemonchiffon;
  min-height: 50px;
  border: 1px solid rebeccapurple;
  margin: 10px 0px;
}

#id2 {
  padding: 20px;
  border: 2px solid blue;
  transition: all 0.5 ease;
}
<script src="https://code.jquery.com/jquery-3.4.0.min.js" integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg=" crossorigin="anonymous"></script>
<div id='id1'>
  <button>click</button>
  <div id="id2"></div>
</div>
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
ted
  • 11,582
  • 6
  • 55
  • 96
  • Possible duplicate of [How can I transition height: 0; to height: auto; using CSS?](https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css) –  Apr 17 '19 at 14:23
  • I don't see how, could you elaborate? – ted Apr 17 '19 at 14:35
  • Instead of apply transition on `height`attribute you apply `max-height`attribute. Use Jquery to calculate the `max-height`by the amount of childs. –  Apr 17 '19 at 14:36
  • But I don't have nor want a max height, the height changes as children are added not as I hover as in this question – ted Apr 17 '19 at 14:37
  • 1
    You can't apply css transition on `height`. You would have to use jquery's `animate`. Check: http://api.jquery.com/animate/ –  Apr 17 '19 at 14:46

2 Answers2

2

I made it work for you. I changed the animations to the element you're appending. #id2 to .child

Use styles used for multiple cases on classes and not on ids as they should be unique.

<div id='id1'>
  <button>click</button>
  <div id="id2"></div>
</div>

#id1 {
  width: 100%;
  transition: all 2 ease;
}

.child {
  background-color: lemonchiffon;
  min-height: 50px;
  border: 1px solid rebeccapurple;
  margin: 10px 0px;
  animation: animateElement linear .3s;
  animation-iteration-count: 1;
}

#id2 {
  padding: 20px;
  border: 2px solid blue;
}


@keyframes animateElement{
  0% {
    opacity:0;
    transform:  scaleY(0) translateY(-100%);
  }
  100% {
    opacity:1;
    transform:  scaleY(1) translateY(0%);
  }
}

$(function() {
  $("#id1 button").click(() => {
    $("#id2").append("<div class='child'>hehe</div>")
  });
});
Koen
  • 131
  • 1
  • 9
0

No CSS property changes when the button is pressed, therefore it is the correct behaviour not to trigger any CSS transition.

Making #id2 grow smoothly as new children are added, some other mechanism must be used.