title: Animating max-height with pure JS?
body: <p>I want to animate the height of a div. This is normally done in CSS by animating the <code>max-height</code> property.</p>
  
  <p>However I need to do this in JS. The div is populated with dynamic content that changes frequently so the actual height is not known ahead of time.</p>
  
  <p>Here is a jsfiddle: <a href="https://jsfiddle.net/vpknxuk8/" rel="noreferrer">https://jsfiddle.net/vpknxuk8/</a></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var box = document.getElementById("box");
  var button = document.getElementById("button");
  var expanded = true;
  
  button.addEventListener('click', function() {
      if (expanded) {
          box.style.maxHeight = 0;
          expanded = false;
      } else {
          box.style.maxHeight = "";
          expanded = true;
      }
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
    margin-top: 20px;
    border: 1px solid black;
    background-color: #4f88ff;
    width: 200px;
    transition: max-height 0.25s linear;
    overflow: hidden;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button id="button"&gt;Click&lt;/button&gt;
  
  &lt;div id="box"&gt;
    Hello World&lt;br&gt;
    This is dynamic content&lt;br&gt;
    The actual height won't be known ahead of time
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>The box should transition between a height of 0 and its default height, but for some reason it isn't animating.</p>
  
  <p>The only other versions of this question on StackOverflow pertain to CSS-only solutions or jQuery solutions.</p>