Alrekr Alrekr - 5 months ago 7
Javascript Question

CSS transition of a div does not animate

When I click a div, I want a second div to expand/collapse. That is done using JS, HTML, and CSS. Now I want the CSS transition to animate.

Right now all I get is a jumping expansion and either a scroll (Edge) or a jump after a wait (Chrome, Opera, Firefox).

I've tried to set height to 1px instead of 0px, but that doesn't change anything.



function growDiv(id) {
var ele = document.getElementById(id);
if (ele.style.height == '100%') {
ele.style.height = '0px';
} else {
ele.style.height = '100%';
}
}

.main {
font-weight: 700;
overflow: hidden;
cursor: pointer;
}
.secondary {
-webkit-transition: height .5s ease;
-moz-transition: height .5s ease;
-ms-transition: height .5s ease;
-o-transition: height .5s ease;
transition: height .5s ease;
overflow: hidden;
padding-left: 20px;
height: 0px;
cursor: pointer;
}

<div class="main" onclick="growDiv('expandable')">
Expand
</div>
<div class="secondary" id="expandable" onclick="growDiv('expandable')">
number1,
<br>number2,
<br>number3,
<br>number4.
</div>





Codepen behaves as I know the full site does, so for good measure; here's the codepen: http://codepen.io/anon/pen/ezJQjM

Answer

Are you willing to use jQuery? It offers some cool animation possibilities, and may accomplish what you are trying to do. This is just a possible alternative to your approach.

Check out my fiddle here:

https://jsfiddle.net/3mo28z1t/11/

<div class="main" id="clicker">
  Expand
</div>
<div class="secondary" id="expandable">
  number1, <br> number2, <br> number3, <br> number4.
</div>

<script>
 $( document ).ready(function() {

$(".secondary").hide();

$(document).ready(
    function(){
        $("#clicker").click(function () {
            $(".secondary").toggle("slow");
        });

    });   

});
</script>