title: Trigger CSS Animation on Click via javascript
body: <p>I have a simple hamburger icon and I want to trigger CSS animation on click via pure javascript(no jquery please). I am doing this by adding and removing a class on hamburger icon when I add the class the CSS animation is happening however when I remove the class the animation is not happening, the hamburger line is coming back abruptly without animating. Basically I want the animation to reverse and come back to original position.</p>
  <p>Here is the code:</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 hamburgerMenu = document.querySelector('.hamburger-menu');
  hamburgerMenu.addEventListener('click', function() {
    var hamburgerMenuSpan2 = document.querySelector('.hamburger-second');
  
    hamburgerMenuSpan2.classList.toggle('hamburger-line-2');
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.hamburger-menu {
    position: absolute;
    top: 20px;
    right: 20px;
  }
  
  .hamburger-line-2 {
    animation-name: animate;
    animation-duration: 3s;
    animation-timing-function: ease-in-out;
    animation-fill-mode: forwards;
    animation-direction: alternate;
  }
  
  @keyframes animate {
    0% {
      width: 40px;
    }
    100% {
      width: 0px;
    }
  }
  
  .hamburger-menu span {
    display: block;
    width: 40px;
    height: 2px;
    background: black;
    margin: 10px 0px;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="hamburger-menu"&gt;
    &lt;span class="hamburger-line-1"&gt;&lt;/span&gt;
    &lt;span class="hamburger-second"&gt;&lt;/span&gt;
    &lt;span class="hamburger-line-3"&gt;&lt;/span&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  <p>Basically I want the hamburger icon line to become 0px width on click with duration and then whenever user clicks again I want the hamburger icon line to become original width starting from 0.</p>